均衡列表中所有列表的长度?

fra*_*oll 8 r list

我有一个列表列表,我希望子列表都具有相同的长度

即,NA如果需要,用s 填充它们,以便它们都达到最长列表的长度.

模拟的例子

list1 <- list(1, 2, 3)
list2 <- list(1, 2, 3, 4, 5)
list3 <- list(1, 2, 3, 4, 5, 6)

list_lists <- list(list1, list2, list3)
Run Code Online (Sandbox Code Playgroud)

我最好的尝试

max_length <- max(unlist(lapply (list_lists, FUN = length))) 
    # returns the length of the longest list

list_lists <- lapply (list_lists, function (x) length (x) <- max_length)
Run Code Online (Sandbox Code Playgroud)

问题,它将我的所有子列表替换为整数= max_length ...

list_lists [[1]]
> [1] 6
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?

989*_*989 5

试试这个(ls你的清单在哪里):

lapply(lapply(sapply(ls, unlist), "length<-", max(lengths(ls))), as.list)
Run Code Online (Sandbox Code Playgroud)


And*_*lin 3

这是您的代码已修复。该函数应该返回x,而不是length(x)。另外,为了清楚起见,我使用了向量,而不是列表。

list1 <- c(1, 2, 3)
list2 <- c(1, 2, 3, 4, 5)
list3 <- c(1, 2, 3, 4, 5, 6)

list_lists <- list(list1, list2, list3)

max_length <- max(unlist(lapply (list_lists, FUN = length))) 

list_lists <- lapply (list_lists, function (x) {length (x) <- max_length;x})

# [[1]]
# [1]  1  2  3 NA NA NA
# 
# [[2]]
# [1]  1  2  3  4  5 NA
# 
# [[3]]
# [1] 1 2 3 4 5 6
Run Code Online (Sandbox Code Playgroud)

对于原始列表,结果是:

# [[1]]
# [[1]][[1]]
# [1] 1
# 
# [[1]][[2]]
# [1] 2
# 
# [[1]][[3]]
# [1] 3
# 
# [[1]][[4]]
# NULL
# 
# [[1]][[5]]
# NULL
# 
# [[1]][[6]]
# NULL
# 
# 
# [[2]]
# [[2]][[1]]
# [1] 1
# 
# [[2]][[2]]
# [1] 2
# 
# [[2]][[3]]
# [1] 3
# 
# [[2]][[4]]
# [1] 4
# 
# [[2]][[5]]
# [1] 5
# 
# [[2]][[6]]
# NULL
# 
# 
# [[3]]
# [[3]][[1]]
# [1] 1
# 
# [[3]][[2]]
# [1] 2
# 
# [[3]][[3]]
# [1] 3
# 
# [[3]][[4]]
# [1] 4
# 
# [[3]][[5]]
# [1] 5
# 
# [[3]][[6]]
# [1] 6
Run Code Online (Sandbox Code Playgroud)