我有一个包含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
答案 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