I have a data.table
with some character variables and numeric/integer variables, I would like to identify a variable that is of type character, and then run the tolower
function to modify case. Here is what I am doing but it does not seem to accomplish the check of type to only operate on character variables:
set.seed(426)
dt <- data.table(a = runif(5), b = sample(LETTERS, 5))
dt
a b
1: 0.8472276 Y
2: 0.1567767 J
3: 0.9817384 L
4: 0.2250681 S
5: 0.5994389 H
sapply(dt, class)
a b
"numeric" "character"
dt2 <- as.data.table(sapply(dt, function(n){
if(class(n) == "character"){
n <- tolower(n)
} else{
n
}
}))
dt2
a b
1: 0.847227579215541 y
2: 0.156776716466993 j
3: 0.981738423462957 l
4: 0.225068145431578 s
5: 0.599438918055966 h
sapply(dt2, class)
a b
"character" "character"
I'm new to the apply family, any insight is appreciated