gpt4 book ai didi

r - 如何绑定(bind)行而不丢失带有字符(0)的行?

转载 作者:行者123 更新时间:2023-12-04 17:14:35 26 4
gpt4 key购买 nike

我有一个类似 L 的列表(来自矢量 split )。

L <- strsplit(c("1 5 9", "", "3 7 11", ""), " ")

# [[1]]
# [1] "1" "5" "9"
#
# [[2]]
# character(0)
#
# [[3]]
# [1] "3" "7" "11"
#
# [[4]]
# character(0)

当我做一个普通的 rbind如下,我失去了所有的 character(0)行。
do.call(rbind, L)
# [,1] [,2] [,3]
# [1,] "1" "5" "9"
# [2,] "3" "7" "11"

我总是要做一个 lapply像下面这样还是我错过了什么?
do.call(rbind, lapply(L, function(x) 
if (length(x) == 0) rep("", 3) else x))
# [,1] [,2] [,3]
# [1,] "1" "5" "9"
# [2,] "" "" ""
# [3,] "3" "7" "11"
# [4,] "" "" ""

首选基本 R 答案。

最佳答案

这是此类场景的定义行为。如 ?rbind 中所写:

For cbind (rbind), vectors of zero length (including NULL) are ignored unless the result would have zero rows (columns), for S compatibility. (Zero-extent matrices do not occur in S3 and are not ignored in R.)



当您检查您的元素时,您会发现这是真的:
length(L[[1]])

[1] 3

length(L[[2]])

[1] 0

但是,如您所见,可能有多种解决方法。

关于r - 如何绑定(bind)行而不丢失带有字符(0)的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55662713/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com