Dataframe within dataframe?

后端 未结 3 1438
孤街浪徒
孤街浪徒 2021-01-04 02:38

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         


        
3条回答
  •  离开以前
    2021-01-04 02:58

    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)
    

提交回复
热议问题