R 将列表重新排列为数据帧,然后
有一个具有不同长度的不同子列表的列表R 将列表重新排列为数据帧,然后,r,list,dataframe,R,List,Dataframe,有一个具有不同长度的不同子列表的列表 l [[1]] 3,4,5,7,8 [[2]] 4,5,7 [[3]] 3,9 [[4]] 6,7,8,10 如何将列表重新排序为COL为子列表1到4的数据帧?其余的应该用NA填充。然后我可以在此数据帧上使用melt吗?您可以尝试以下方法: #create some dummy date a<-list(c(3,4,5,7,8),c(4,5,7),c(3,9),c(6,7,8,10)) #get the longest vector m<-m
l
[[1]] 3,4,5,7,8
[[2]] 4,5,7
[[3]] 3,9
[[4]] 6,7,8,10
如何将列表重新排序为COL为子列表1到4的数据帧?其余的应该用NA填充。然后我可以在此数据帧上使用melt吗?您可以尝试以下方法:
#create some dummy date
a<-list(c(3,4,5,7,8),c(4,5,7),c(3,9),c(6,7,8,10))
#get the longest vector
m<-max(sapply(a,length))
#fill in the sublists with NAs so that they all have the same length
as.data.frame(sapply(a,function(x){length(x)<-m;x}))
# V1 V2 V3 V4
#1 3 4 3 6
#2 4 5 9 7
#3 5 7 NA 8
#4 7 NA NA 10
#5 8 NA NA NA
#创建一些虚拟日期
a您可以尝试以下方法:
#create some dummy date
a<-list(c(3,4,5,7,8),c(4,5,7),c(3,9),c(6,7,8,10))
#get the longest vector
m<-max(sapply(a,length))
#fill in the sublists with NAs so that they all have the same length
as.data.frame(sapply(a,function(x){length(x)<-m;x}))
# V1 V2 V3 V4
#1 3 4 3 6
#2 4 5 9 7
#3 5 7 NA 8
#4 7 NA NA 10
#5 8 NA NA NA
#创建一些虚拟日期
带有stringi
包的
library(stringi)
(Res <- stri_list2matrix(a))
# [,1] [,2] [,3] [,4]
# [1,] "3" "4" "3" "6"
# [2,] "4" "5" "9" "7"
# [3,] "5" "7" NA "8"
# [4,] "7" NA NA "10"
# [5,] "8" NA NA NA
库(stringi)
(Res带stringi
包
library(stringi)
(Res <- stri_list2matrix(a))
# [,1] [,2] [,3] [,4]
# [1,] "3" "4" "3" "6"
# [2,] "4" "5" "9" "7"
# [3,] "5" "7" NA "8"
# [4,] "7" NA NA "10"
# [5,] "8" NA NA NA
库(stringi)
(Res您可以执行以下操作:
下面的代码将添加零,而不是NA
a<-list(c(3,4,5,7,8),c(4,5,7),c(3,9),c(6,7,8,10))
n.col <- vapply(a, length, 1L)
mat <- matrix(0, nrow = length(a), ncol = max(n.col))
rand <- cbind(rep(seq_along(n.col), times = n.col), sequence(n.col))
M[rand] <- unlist(a, use.names = FALSE)
M2 <- t(M)
print(M2)
# [,1] [,2] [,3] [,4]
#[1,] 3 4 3 6
#[2,] 4 5 9 7
#[3,] 5 7 0 8
#[4,] 7 0 0 10
#[5,] 8 0 0 0
a您可以执行以下操作:
下面的代码将添加零,而不是NA
a<-list(c(3,4,5,7,8),c(4,5,7),c(3,9),c(6,7,8,10))
n.col <- vapply(a, length, 1L)
mat <- matrix(0, nrow = length(a), ncol = max(n.col))
rand <- cbind(rep(seq_along(n.col), times = n.col), sequence(n.col))
M[rand] <- unlist(a, use.names = FALSE)
M2 <- t(M)
print(M2)
# [,1] [,2] [,3] [,4]
#[1,] 3 4 3 6
#[2,] 4 5 9 7
#[3,] 5 7 0 8
#[4,] 7 0 0 10
#[5,] 8 0 0 0
a