如何解决为什么我建立的R函数产生错误的输出?
我建立了一个R函数,该函数产生错误的输出。这是一个简化的版本:
# Dataset
test <- data.frame( color = c("blue","green","black","white","gray","purple"))
test$color <- as.character(test$color)
# Build function to recode values which matches the input into a new output
fun_recode <- function(regex_input,regex_output) {
reg_start <- ".*"
reg_end <- ".*"
index <- vector()
for (i in 1:length(regex_input)) {
index_1 <- grep(pattern = paste0(reg_start,regex_input[i],reg_end),x = test$color)
index <- c(index,index_1)
}
test[index,] <- regex_output
}
# Set arguments
regex_input <- c("a","y")
regex_output <- "GOT IT!"
# Call function
fun_recode(regex_input,regex_output)
我得到此输出(注意已更改):
正确的输出应为:
请告知我的功能出了什么问题。预先感谢。
解决方法
-
在函数中更改的对象不会反映在全局环境中,除非您使用不推荐使用的
<<-
或assign
。 -
您可以将
regex_input
折叠成一个字符串,以避免使用for
循环。 -
不需要
reg_start
和reg_end
。另外,最好将数据帧显式传递到函数中。
尝试使用此功能:
fun_recode <- function(data,regex_input,regex_output) {
data$color[grep(paste0(regex_input,collapse = "|"),data$color)] <- regex_output
return(data)
}
# Set arguments
regex_input <- c("a","y")
regex_output <- "GOT IT!"
# Call function
test1 <- fun_recode(test,regex_output)
test1
# color
#1 blue
#2 green
#3 GOT IT!
#4 white
#5 GOT IT!
#6 purple
因此,您的函数中有问题的地方就是第1点。在函数中所做的更改保留在函数中。您需要return
从函数中更改的值。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。