kyg
kyg

Reputation: 105

Why did the R function I built produce the wrong output?

I built an R function that produces the wrong output. Here is a simplified version:

# 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)

I get this output (noting changed):

enter image description here

The correct output should be:

enter image description here

Please advise what is wrong with my function. Thanks in advance.

Upvotes: 2

Views: 106

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388807

  1. Objects changed in the function do not get reflected in the global environment unless you use <<- or assign which is not recommended anyway.

  2. You can collapse regex_input into one string to avoid using for loop.

  3. There is no need for reg_start and reg_end. Also, it is better to pass dataframe explicitly into the function.

Try this function :

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_input, regex_output)
test1
#    color
#1    blue
#2   green
#3 GOT IT!
#4   white
#5 GOT IT!
#6  purple

So the thing which is wrong in your function is point 1. The change done in the function remains in the function. You need to return the changed value from the function.

Upvotes: 2

Related Questions