gpt4 book ai didi

rbind 基于列名并排除不匹配

转载 作者:行者123 更新时间:2023-12-02 06:16:30 26 4
gpt4 key购买 nike

示例数据:

l <- list(x=data.frame(X1=1,X2=2,X3=3,X4=4,X5=5),
y=data.frame(X1=6,X8=7,X4=8,X9=9,X5=10),
z=data.frame(X1=11,X2=12,X3=13,X4=14,X5=15)
)

我想根据预先指定的列名rbind此列表,以便列名(及其列位置匹配)。

# these are pre-defined columns names we want to `rbind` if no match, exclude the list entry
col <- c("X1","X2","X3","X4","X5")

所需的输出应该是data.frame:

  X1  X2  X3  X4  X5
1 2 3 4 5
11 12 13 14 15

编辑:可能是这样的:

do.call(rbind, lapply(l, function(x) x[!any(is.na(match(c("X1","X2","X3","X4","X5"), names(x))))]))

最佳答案

这是一种方法:

match_all_columns <- function (d, col) {
if (all(names(d) %in% col)) {
out <- d[, col]
} else {
out <- NULL
}
out
}
# or as a one-liner
match_all_columns <- function (d, col) if (all(names(d) %in% col)) d[col]

matched_data <- lapply(l, match_all_columns, col)
result <- do.call(rbind, matched_data)
result
# X1 X2 X3 X4 X5
# x 1 2 3 4 5
# z 11 12 13 14 15

rbind 知道只忽略 NULL 元素。

编辑:我用 d[col] 交换了 d[, col] 因为 a) 它看起来更好,b) 它防止数据帧被丢弃到一个向量如果 col 只有一个元素,并且 c) 我认为它在大型数据帧上的性能稍微好一些。

关于rbind 基于列名并排除不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29472663/

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