0

I'm trying to write a function that changes the specific values in my dataframe. I've got a dataframe that has several numeric values and I want to change these as strings. For instance, in the "type" column of the data frame, I want to change 1 to the string 'foil', 2 to the string 'repeat', etc. I was able to come up with some code to do it on a single type, which works nicely:

mydata[which(mydata[,'type'] == 1),'type'] <- 'foil'

Since that worked on its own, I tried to create the following function:

recode <- function(column, value1, value2) {
  mydata[which(mydata[,column] == value1), column] <- value2
}

To test it, I run the following code:

recode('type',1,'foil')

I don't get any errors when I run it, but it doesn't change anything. I can get it to work correctly when I define the variables manually and run the code for the function like this:

column <- 'type'
value1 <- 1
value2 <- 'foil'
mydata[which(mydata[,column] == value1), column] <- value2

I'm not sure why the same line of code works outside the function, but doesn't work inside the function. Any help would be greatly appreciated!

D. Bjornn
  • 1
  • 2
  • Your function should `return()` the full (modified) data frame. And then you should assign the result, like any other R function. `my_modified_data <- recode('type', 1, 'foil')`. It would be a much better function if it also took the data frame as input, otherwise it will only work to modify data frames named `mydata`. – Gregor Thomas Nov 28 '16 at 20:40
  • The function modifies a local copy. You should return a value. – Matthew Lundberg Nov 28 '16 at 20:40
  • Functions are like Las Vegas: what's happens there stays there. Your function should return the modified object `mydata`, and then you would call it like `mydata <- recode(mydata,....)` – joran Nov 28 '16 at 20:40

0 Answers0