将n个元素的列表拆分为n个向量的一个数据帧

时间:2019-06-20 10:53:13

标签: r

我有一个包含5个长度不等的r的列表

  

r

$First
[1] "Jan"   "feb"   "March" "Ram"  

$Second
[1] "Jan"   "feb"   "April"

$Third
[1] "Jan"   "feb"   "May"   "Shyam"

$Fourth
[1] "Jan"  "feb"  "June" "abcd" "July"

$Fifth
[1] "Jan"     "feb"     "asdfgg"  "dfhfhsa" "qwer" 

现在,我想在删除前两个公共值后将此列表转换为五个向量的数据帧。

我尝试了很长的方法。首先,我将列表的每个元素转换为单个数据帧,然后将前两个值切成薄片。

we<-r$First[3:4]

me<-r$Second[3]

er<-r$Third[3:4]

rt<-r$Fourth[3:5]

ty<-r$Fifth[3:5]

我相信还有另一种解决方法。我是R的新手,我找不到。

输出应类似于

   First   Second  Third   Fourth   Fifth    
1  March   April    May     June     asdfgg
2  Ram    NA        Shyam    abcd    dfhfhsa
3   NA    NA          NA      July    qwer

3 个答案:

答案 0 :(得分:1)

我们可以首先使用Reduce找到两个公共值,然后使用sapply从每个列表元素中删除它们,然后通过设置子集将其余元素转换为数据帧

common_vals <- head(Reduce(intersect, r), 2)
r1 <- sapply(r, function(x) x[!x %in% common_vals])
n <- max(lengths(r1))
data.frame(sapply(r1, `[`, 1:n))

#  First Second Third Fourth   Fifth
#1 March  April   May   June  asdfgg
#2   Ram   <NA> Shyam   abcd dfhfhsa
#3  <NA>   <NA>  <NA>   July    qwer

数据

r <- list(First = c("Jan","feb","March","Ram" ), Second = c("Jan","feb","April"), 
      Third = c("Jan","feb","May" ,"Shyam"), 
      Fourth = c("Jan","feb" ,"June","abcd","July"), 
      Fifth = c("Jan","feb","asdfgg","dfhfhsa","qwer"))

答案 1 :(得分:1)

我们可以在tidyverse中,通过discard设置具有list个元素的intersect个元素并将不相等的list长度转换为{{1 }}和matrix中的stri_list2matrix

stringi

或者在没有管道的单行中

library(tidyverse)
library(stringi)
map(r, ~  discard(.x, .x %in% reduce(r, intersect))) %>% 
   stri_list2matrix
#      [,1]    [,2]    [,3]    [,4]   [,5]     
#[1,] "March" "April" "May"   "June" "asdfgg" 
#[2,] "Ram"   NA      "Shyam" "abcd" "dfhfhsa"
#[3,] NA      NA      NA      "July" "qwer"   

数据

stri_list2matrix(map(r, discard, `%in%`, reduce(r, intersect)))

答案 2 :(得分:0)

如果您只想丢弃每个向量的前两个元素并转换为data.frame,那么就足够了:

nmax <- max(lengths(r))
data.frame(lapply(r, "[", 3:nmax))

#   First Second Third Fourth   Fifth
# 1 March  April   May   June  asdfgg
# 2   Ram   <NA> Shyam   abcd dfhfhsa
# 3  <NA>   <NA>  <NA>   July    qwer