Home > database >  Extract the first, second, third , … sub-element from a list in R and store as list
Extract the first, second, third , … sub-element from a list in R and store as list

Time:08-06

I have the following list which is composed of 12 elements and each element is a vector of length 15.

set.seed(100)
list_data <- replicate(12, sample.int(1000,15),simplify = F)

I would like to extract the first, second, ..., and 15th element of the sublist as follows:

sapply(list_data, '[[',1)
sapply(list_data, '[[',2)
...
sapply(list_data, '[[',15)

and store them in a list:

list(sapply(list_data, '[[',1), sapply(list_data, '[[',2),sapply(list_data, '[[',3),
sapply(list_data, '[[',4), ...,sapply(list_data, '[[',15))

So, in the end, there should be a list of length 15 with each element a list containing a vector of length 12. I am wondering if I can do it without for loop and maybe with a combination of lapply and sapply?

CodePudding user response:

Yes

lapply(1:15, function(i) sapply(list_data, '[', i))

CodePudding user response:

library(data.table)
transpose(list_data)

results in

[[1]]
 [1] 714 183 948 158 920 883 952 298 314 147 694 895

[[2]]
 [1] 503 299 560 733 171 923 406 844 538 863 170 316

[[3]]
 [1] 358 504 288  87 519 430 978 421 233 663 387 813

[[4]]
 [1] 624 466 341 607 703 955 949 666  48 844 742 364

[[5]]
 [1] 985 957 347 865 449 942 643 490 255 794 336 805

[[6]]
 [1] 718 908 167 223 393 254 133 871 848 261 730 490

[[7]]
 [1] 919 307 377 925 660 965 556 792 118 759 422 964

[[8]]
 [1] 470 456 784 732 910  47 853 396  37 334 728 100

[[9]]
 [1] 966 146 971 251 363 439 156 137 222 296 427 201

[[10]]
 [1] 516 793 628 543 846 943 948 250 731 879 723 922

[[11]]
 [1] 823 258 450 694 600 708 757 363 658 849 900 283

[[12]]
 [1] 838 435 966 425 387  12 281 567 328 997 714 927

[[13]]
 [1]  98 324 605 489 878 947 554 843  91 222 494 942

[[14]]
 [1] 903  68 301 297 420 121 655 703 584 448 818  71

[[15]]
 [1]   7 510 670 502 371  16 185 291 194 223 780 661

CodePudding user response:

If you prefer using tidyverse functions, you could use

library(purrr)

list_data %>% transpose() %>% simplify_all()
  • Related