R - loop iteratively through lists and create a dataframe

Multi tool use
Multi tool use


R - loop iteratively through lists and create a dataframe



I have a long list of lists (> 100k) and need to iteratively loop through each list and extract the "id" - which i can do easily by constructing lapply in a for loop.


lapply



Here is an example of the lists:


l1 <- list(id="002e2b45555652749339ab9c34359fb6", key="2", value="xx")
l2 <- list(id="002e2b433226527493jsab9c34353fb6", key="4", value="zz")
l3 <- list(list1, list2)



I do the looping with:


for(i in 1:20) {
lapply(l3$id[[i]][1], function (x) print(x))
}



Basically printing all the elements of each list of the id - which is nice.
I ultimately want to construct a matrix / dataframe with all the "ids" in rows. What bugs me is, the print in my loop works well, printing out all ids from all the lists - although I cannot bind my rows to a dataframe or a matrix etc. i was trying out something like - ain't doing what i want (although not getting an error etc.)


for(i in 1:20) {
lapply(l3$id[[i]][1], function (x) rbind(x))
}



SO the desired output shall be (preferrably as a dataframe).


[1] "002e2b45555652749339ab9c3400cc52"
[1] "002e2b45555652749339ab9c34040525"




2 Answers
2



using base R:


s=aggregate(.~ind,stack(setNames(l3,1:length(l3))),identity)
ind values.1 values.2 values.3
1 1 002e2b45555652749339ab9c34359fb6 2 xx
2 2 002e2b433226527493jsab9c34353fb6 4 zz



if you just need the id's


s$values[,1]
[1] "002e2b45555652749339ab9c34359fb6" "002e2b433226527493jsab9c34353fb6"



If you want a vector of the IDs you can do


sapply(l3, "[[", "id")



or using tidyverse functions


purrr::map_chr(l3, "id")



No need for loops for stuff like this in R.





awesome ! thank you - hadn't had purrr on my radar though
– t.jirku
Jul 2 at 14:35






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

lSc5KWYR0,R 9ZYZFt9 9y6Xpg,WyZ,5,Wkc 86lKPzvVp0xtUiU7,ifoho,iSq CfPNf73mXd,pJ
Psb2Z50sB,RZ97bSBYEcDCSZQFpD5JF05CF,psTg zFAl,sWcbyjoLe,Led LX0gI GvAva

Popular posts from this blog

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?

Create weekly swift ios local notifications