首页 > 解决方案 > Sorting over a list inside a dataframe in R

问题描述

I got a dataframe where a column (in this case, V2) is a list, like this:

df <- structure(list(V1 = c(1, 2, 3), 
                     V2 = list(c(1, 2, 78, 3), c(9, 4, 78, 8), c(33, 18, 25, 20, 10, 23))), 
                row.names = c(NA, -3L), class = "data.frame")

#  V1                     V2
#1  1            1, 2, 78, 3
#2  2            9, 4, 78, 8
#3  3 33, 18, 25, 20, 10, 23

I need to rearrange the elements on each row of V2. I've tried lapplying a sort over V2, but can't get it to work.

Here is my desired output:

#  V1                     V2
#1  1            1, 2, 3, 78 
#2  2            4, 8, 9, 78
#3  3  10, 18, 20, 23, 25,33

Any suggestions are very much appreciated!

标签: rlistsortinglapply

解决方案


简单地:

df$V2 <- lapply(df$V2, sort)

推荐阅读