Reputation: 8494
I have an example dataframe:
a <- c(1:5)
b <- c("Cat", "Dog", "Rabbit", "Cat", "Dog")
c <- c("Dog", "Rabbit", "Cat", "Dog", "Dog")
d <- c("Rabbit", "Cat", "Dog", "Dog", "Rabbit")
e <- c("Cat", "Dog", "Dog", "Rabbit", "Cat")
f <- c("Cat", "Dog", "Dog", "Rabbit", "Cat")
df <- data.frame(a,b,c,d,e,f)
I want to recode certain variables within this dataframe (for example columns c, d and e).
So far I have:
library(car) # Contains recode function
survey[, 3:5] <- lapply(survey[ , 3:5] ,
FUN = function(x) recode(x, "Cat =0; Dog =1; Rabbit"=2)))
But this gives an error message. Could anyone suggest how the function should read?
Also, if I added extra columns before, is it possible to do a range of columns using the first and the last?
i.e. df$c:df$e
Any help would be gratefully received.
Upvotes: 1
Views: 652
Reputation: 98579
There were couple of mistakes in your code. First, there where too much )
at the end of code. Next, for the recode()
function levels you are changing should be in ''
. If you add argument as.factor.result=FALSE
then result will be numeric.
df[,3:5]<-sapply(df[ , 3:5] ,
FUN = function(x) recode(x, "'Cat' =0; 'Dog' =1; 'Rabbit'=2",
as.factor.result=FALSE))
Upvotes: 2