r - 从数据框中对一列进行子集化,将子集保留为数据框

标签 r dataframe subset

我有一个包含过滤器的表格,例如

> X = data.frame(filter1=c(1,1,1),filter2=c(1,1,0),filter3=c(1,0,0))
> X
  filter1 filter2 filter3
1       1       1       1
2       1       1       0
3       1       0       0

我喜欢根据条件选择过滤器:

> selected_filters = c(1:2)
> X[,paste0("filter",c(selected_filters))]
  filter1 filter2
1       1       1
2       1       1
3       1       0

但是,如果我只选择一列,数据框将转换为列表

> selected_filters = c(2)
> X[,paste0("filter",c(selected_filters))]
[1] 1 1 0

如何仅选择一列将结果保留为数据框?期望的结果看起来像

  filter2
1       1
2       1
3       0

最佳答案

我们需要drop = FALSE

X[, paste0("filter",c(selected_filters)), drop = FALSE]
#   filter2
#1       1
#2       1
#3       0

如果我们查看?Extract,就会显示用法

x[i, j, ... , drop = TRUE]

在描述中,它说

drop - For matrices and arrays. If TRUE the result is coerced to the lowest possible dimension (see the examples). This only works for extracting elements, not for the replacement. See drop for further details.


请注意,subset 行为有所不同,因为默认情况下它是 drop = FALSE

subset(X, select = paste0("filter",c(selected_filters)))

关于r - 从数据框中对一列进行子集化,将子集保留为数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55701894/

相关文章:

r - H2O R 中的子集化

请求用户识别文件位置并从 R 中的文件位置自动提取变量名

python - 从 python 中的现有列创建新列

r - 根据另一个数据框中的值对数据框进行子集化

r 循环用于过滤每一列

Pandas 将切割中的列添加到 DataFrame

r - 如何根据名称对列表的列表进行子集化

r - 在分组数据帧上进行变异+过滤与汇总相比有什么缺点吗?

r - 根据引用列中的值是大于还是小于 0 对数据框进行子集化

r - R与Tableau连接时如何返回向量?