Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何一次在R中获取具有相同列名的所有列?_R - Fatal编程技术网

如何一次在R中获取具有相同列名的所有列?

如何一次在R中获取具有相同列名的所有列?,r,R,假设我有以下数据框: > test <- cbind(test=c(1, 2, 3), test=c(1, 2, 3)) > test test test [1,] 1 1 [2,] 2 2 [3,] 3 3 > new_df <- test[, "test"] > new_df [1] 1 2 3 如何在本例中获取所有名为“test”的列,并在单个命令中将它们放入新的数据帧中?在我的实际数据中,我有许多列具

假设我有以下数据框:

> test <- cbind(test=c(1, 2, 3), test=c(1, 2, 3))
> test
     test test
[1,]    1    1
[2,]    2    2
[3,]    3    3
> new_df <- test[, "test"]
> new_df
[1] 1 2 3

如何在本例中获取所有名为“test”的列,并在单个命令中将它们放入新的数据帧中?在我的实际数据中,我有许多列具有重复的列名,我不知道列的索引,因此无法按数字获取它们。

出于实际原因,不建议使用相同的列名。但是,我们可以通过比较(
==
)得到一个逻辑向量,并使用它来提取列

i1 <- colnames(test) == "test"
new_df <- test[, i1, drop = FALSE]
或者循环查看
唯一的
列名,并使用
lapply循环查看
=

lst2 <- lapply(unique(colnames(test)), function(nm) 
             test[, colnames(test) == nm, drop = FALSE])

lst2谢谢,这就是我需要的解释你想要这样的东西吗<代码>测试[,grepl(“测试”,colnames(测试))]
lst2 <- lapply(unique(colnames(test)), function(nm) 
             test[, colnames(test) == nm, drop = FALSE])