简体   繁体   English

如何将长列表中的某些项目转换为 R 中的数据框?

[英]How to convert certain items from a long list to data frame in R?

I have a list which is 4500 elements long.我有一个 4500 个元素长的列表。 Each list is of length 7. Will it be possible to extract certain items from each list and convert to a data frame.每个列表的长度为 7。是否可以从每个列表中提取某些项目并转换为数据框。 Below is an example下面是一个例子

List1 <- list(Name = "Peter" , Age = 25 , State = "Texas" , Occupation = "Analyst1" , Salary =5000)

List2 <- list(Name = "Susan" , Age = 30 , State = "New York" , Occupation = "Analyst11" , Salary =7000)

List3 <- list(Name = "John" , Age = 35 , State = "New Jersey" , Occupation = "Manager" , Salary =10000)
List4 <- list(Name = "Sam" , Age = 30 , State = "Florida" , Occupation = "Analyst1" , Salary =5000)
List5 <- list(Name = "Judy" , Age = 30 , State = "California" , Occupation = "Analyst11" , Salary =7000)
FinalList <- list(List1 , List2, List3 , List4 , List5)

I would like to create a data frame with columns Name, Age and Salary.我想创建一个包含 Name、Age 和 Salary 列的数据框。 I tried using do.call like我尝试使用 do.call 之类的

 FinalResult <- do.call(rbind ,FinalList[][-c(3,4)] )

Which is creating a dataframe as shown below:它正在创建一个 dataframe ,如下所示:

 #     name    Age State        Occupation  Salary
 #[1,] "Peter" 25  "Texas"      "Analyst1"  5000  
 #[2,] "Sam"   30  "Florida"    "Analyst1"  5000  
 #[3,] "Judy"  30  "California" "Analyst11" 7000  

But what I would like to create is但我想创造的是

 #         name    Age   Salary
 #[1,]    "Peter"  25    5000  
 #[2,]    "Susan"  30    7000  
 #[3,]    "John"   35    10000 
 #[4,]    "Sam"    30    5000  
 #[5,]    "Judy"   30    7000  

Can anyone help me with this?谁能帮我这个? Thank you.谢谢你。

I think what you were trying to do was:我认为你试图做的是:

do.call(rbind ,FinalList)[, -c(3, 4)]
#If needed as dataframe
#do.call(rbind.data.frame,FinalList)[, -c(3, 4)]

Or probably simpler using dplyr或者使用dplyr可能更简单

library(dplyr)
bind_rows(FinalList) %>% select(-(3:4))

and data.tabledata.table

library(data.table)
rbindlist(FinalList)[, -c(3, 4)]

We can use unnest_wider我们可以使用unnest_wider

library(purrr)
library(tidyr)
tibble(col = FinalList) %>%
    unnest_wider(c(col)) %>%
    dplyr::select(-c(3:4))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM