I'm trying to create a function to recode variables into a new variable, based on the coding provided in one variable, and the skip pattern in another.
I've created a trivial example:
data <- data.frame(A=1:4, B=c(1,1,1,2))
My function is as follows:
recode_4scale <- function (var, name, skip, df){
df$name <- df$var #generate new variable
df[which(df$skip==2),"name"] <- 5 #replace with 5 if skip pattern
df[is.na(df$var),"name"] <- 6 #replace with 6 if missing
df$name <- df$name == 3 | df$name==4 #code as true if 3 or 4
df$name <- as.factor(df$name)
return (df)
}
data1<-recode_4scale(A, new, B, data)
I get: Warning message: In is.na(df$var) : is.na() applied to non-(list or vector) of type 'NULL'
What I expect to get by running it line by line:
data$new <- data$A
data[which(data$B==2),"new"] <- 5
data[is.na(data$A),"new"] <- 6
data$new <- data$new == 3 | data$new == 4
data$new <- as.factor(data$new)
data$new
[1] FALSE FALSE TRUE FALSE
Levels: FALSE TRUE
I believe I'm having trouble passing the names in, given that I can't get anything out of even the most simple function.
Any idea what's going wrong here? (I also know that this is not the best way to write this thing in general, new employee fixing old code, will improve it once I get it running)