0

I am writing an anonymous function to loop through a data.table and change any factor variable to a character. I tried the code below, but I receive an error. My actual data.table could have a factor variable in any order, hence why I'm using lapply. Also please share any other ways to do this, but I would like my way answered as well and thanks.

test <- sample[, lapply(.SD, function(x){ 
  if(is.factor(x)){
    as.character(x)}
})
]


sample <- data.table(A = as.factor(1:5), B = as.character(letters[1:5]), C = as.factor(10:14))
user3067851
  • 524
  • 1
  • 6
  • 20

1 Answers1

1

You can't refer to x until you've declared it in function(x)

sample[,lapply(.SD, function(x) if(is.factor(x)) as.character(x) else x)]

You don't even need to use data.table syntax:

data.frame(lapply(sample, function(x) if(is.factor(x)) as.character(x) else x))

  A B  C
1 1 a 10
2 2 b 11
3 3 c 12
4 4 d 13
5 5 e 14
Señor O
  • 17,049
  • 2
  • 45
  • 47