I need to sort the elements of a 'list' column of data.table in alphabetical order and coerce them to a character vector in another intermediate column of R's data.table. Currently, not able to spot the error for the 1st row.
Following code used to generate the original data.table:
my_dt <- data.table(A = rep(1:5, 3), B = rnorm(15, mean=10, sd=2), C = list(c("mango", "pear", "apple")))
Here col. C is a list with repeating elements of "mango", "pear" and "apple" across all the 15 rows of my_dt
Example: my_dt$C[1] yields:
[[1]]
[1] "mango" "pear" "apple"
Next, I want to sort the individual elements for each row and store them in col. D of my_dt. I am using the following code to sort and populate task:
for (lmn in 1:nrow(my_dt)){
word1 <- sapply(my_dt$C[lmn], '[[', 1)
word2 <- sapply(my_dt$C[lmn], '[[', 2)
word3 <- sapply(my_dt$C[lmn], '[[', 3)
my_dt$D[lmn] <- list(sort(c(word1, word2, word3)))
}
However, on printing the output i.e. my_dt, I see the following:
A B C D
1: 1 7.781597 mango,pear,apple apple
2: 2 10.267061 mango,pear,apple apple,mango,pear
3: 3 10.670469 mango,pear,apple apple,mango,pear
4: 4 10.252527 mango,pear,apple apple,mango,pear
5: 5 10.605396 mango,pear,apple apple,mango,pear
6: 1 13.054545 mango,pear,apple apple,mango,pear
7: 2 12.401846 mango,pear,apple apple,mango,pear
8: 3 11.094550 mango,pear,apple apple,mango,pear
9: 4 10.220841 mango,pear,apple apple,mango,pear
10: 5 11.452469 mango,pear,apple apple,mango,pear
11: 1 11.827297 mango,pear,apple apple,mango,pear
12: 2 6.918918 mango,pear,apple apple,mango,pear
13: 3 9.757636 mango,pear,apple apple,mango,pear
14: 4 13.432524 mango,pear,apple apple,mango,pear
15: 5 10.648629 mango,pear,apple apple,mango,pear
I am not sure why 1st entry under col. D shows only apple as compared to the rest of the rows under the same column which have all 3 sorted elements i.e. apple, mango and pear. Ideally, I would like to have these entries consistent across col. D and not partially populated as seen for Row # 1.
Thank you in advance.