r - 如何从 data.frame 中提取单个列作为 data.frame?

标签 r dataframe subset

假设我有一个 data.frame:

df <- data.frame(A=c(10,20,30),B=c(11,22,33), C=c(111,222,333))
  A  B  C
1 10 11 111
2 20 22 222
3 30 33 333

如果我选择两列(或更多列),我会得到一个 data.frame:

x <- df[,1:2]
   A  B
 1 10 11
 2 20 22
 3 30 33

这就是我想要的。但是,如果我只选择一列,我会得到一个数字向量:

x <- df[,1]
[1] 1 2 3

我尝试使用 as.data.frame(),它不会更改两列或更多列的结果。对于一列,它确实返回一个 data.frame,但不保留列名称:

x <- as.data.frame(df[,1])
     df[, 1]
1       1
2       2
3       3

我不明白为什么它会这样。在我看来,如果我提取一列、两列或十列,应该没有什么区别。 IT 应该始终返回向量(或矩阵)或始终返回 data.frame(具有正确的名称)。我缺少什么?谢谢!

注意:这不是关于矩阵的问题的重复,因为矩阵和 data.frame 是 R 中根本不同的数据类型,并且与 dplyr 的工作方式不同。有几个答案适用于 data.frame 但不适用于矩阵。

最佳答案

使用drop=FALSE

> x <- df[,1, drop=FALSE]
> x
   A
1 10
2 20
3 30

从文档中(参见 ?"[" )您可以找到:

If drop=TRUE the result is coerced to the lowest possible dimension.

关于r - 如何从 data.frame 中提取单个列作为 data.frame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21025609/

相关文章:

python - 在具有多个具有不同值的日期时间列的 DataFrame 中设置日期时间索引

python - 按日期时间 Pandas 数据框索引失败

r - 使用另一个 data.table 子集一个 data.table

r - R : Error in fix. by(by.x, x) 中的合并问题: 'by' 必须指定唯一有效的列

r - R中的非缩放神经网络数字矩阵

python - 当我使用元素乘法时,R 和 Python 之间的广播规则不同 (*)

python - 从cassandra读取大数据到python dataframe(内存错误)

python - 使用索引对 pandas 数据帧中的列进行子集化

python - 从大型 CSV 创建代表性样本

r - 如何 pivot_long 对不匹配日期的 date-var 组合?