lets say I have a dataframe data
with numeric column col
is_class <- function(x){
return(class(x['col']))
}
data['class'] <- apply(data, 1, is_class)
should, to my understanding be equivalent to:
data['class2'] <- class(data$col)
However.
all(data['class'] == 'character')
is TRUE
all(data['class2'] == 'numeric')
is TRUE
It appears that apply()
converts each row to all characters. Which makes then performing any numeric operation very difficult.
as below:
times_two <- function(x){
return(x['col']*2)
}
data['col2'] <- apply(data, 1, times_two)
Error in x["col"] * 2: non-numeric argument to binary operator
Traceback:
returns
1. apply(data, 1, times_two)
2. FUN(newX[, i], ...)