Consider this example:
df <- data.frame(id=1:10,var1=LETTERS[1:10],var2=LETTERS[6:15])
fun.split <- function(x) tolower(as.character(x))
df$new.letter
The reason is because you assigned a single new column to a 2 column matrix
output by apply
. So, the result will be a matrix
in a single column. You can convert it back to normal data.frame with
do.call(data.frame, df)
A more straightforward method will be to assign 2 columns and I use lapply
instead of apply
as there can be cases where the columns are of different classes. apply
returns a matrix
and with mixed class, the columns will be 'character' class. But, lapply
gets the output in a list
and preserves the class
df[paste0('new.letters', names(df)[2:3])] <- lapply(df[2:3], fun.split)