Reputation: 69
I have a data frame in R which has a column of list type that contains four numbers:
Size
Ford 1,2,3,4
Gm 2,3,5,6
Nissan 2,3,4,5
Toyota 1,2,2,4
here car names (Ford etc) are row names and Size ("1,2,3,4" etc) is a column of lists.
I would like to sort this data frame by the 3rd number in column Size so we get the following result:
Size
Toyota 1,2,2,4
Ford 1,2,3,4
Nissan 2,3,4,5
Gm 2,3,5,6
In a complete example I have many columns in each row but I still want to do sorting by the 3rd value in Size column.
Upvotes: 0
Views: 438
Reputation: 93938
Something like below will work - I'll remake the data first:
dat <- data.frame(
ID=1:4,
Size=I(list(1:4,c(2,3,5,6),2:5,c(1,2,2,4))),
row.names=c("Ford","Gm","Nissan","Toyota")
)
Which looks like:
ID Size
Ford 1 1, 2, 3, 4
Gm 2 2, 3, 5, 6
Nissan 3 2, 3, 4, 5
Toyota 4 1, 2, 2, 4
Then order it:
dat[order(sapply(dat$Size,"[",3)),]
ID Size
Toyota 4 1, 2, 2, 4
Ford 1 1, 2, 3, 4
Nissan 3 2, 3, 4, 5
Gm 2 2, 3, 5, 6
Upvotes: 4