为什么我建立的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)

我得到此输出(注意已更改):

enter image description here

正确的输出应为:

enter image description here

请告知我的功能出了什么问题。预先感谢。

解决方法

  1. 在函数中更改的对象不会反映在全局环境中,除非您使用不推荐使用的<<-assign

  2. 您可以将regex_input折叠成一个字符串,以避免使用for循环。

  3. 不需要reg_startreg_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从函数中更改的值。