This question already has an answer here:
这个问题在这里已有答案:
- How to subset matrix to one column, maintain matrix data type, maintain row/column names? 1 answer
- 如何将矩阵子集化为一列,维护矩阵数据类型,维护行/列名称? 1个答案
Say I have a data.frame:
说我有一个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
If I select two (or more) columns I get a data.frame:
如果我选择两个(或更多)列,我会得到一个data.frame:
x <- df[,1:2]
A B
1 10 11
2 20 22
3 30 33
This is what I want. However, if I select only one column I get a numeric vector:
这就是我要的。但是,如果我只选择一列,我会得到一个数字向量:
x <- df[,1]
[1] 1 2 3
I have tried to use as.data.frame(), which does not change the results for two or more columns. it does return a data.frame in the case of one column, but does not retain the column name:
我曾尝试使用as.data.frame(),它不会更改两列或更多列的结果。它确实在一列的情况下返回data.frame,但不保留列名:
x <- as.data.frame(df[,1])
df[, 1]
1 1
2 2
3 3
I don't understand why it behaves like this. In my mind it should not make a difference if I extract one or two or ten columns. IT should either always return a vector (or matrix) or always return a data.frame (with the correct names). what am I missing? thanks!
我不明白为什么它会像这样。在我看来,如果我提取一个或两个或十个列,它应该没有区别。 IT应始终返回向量(或矩阵)或始终返回data.frame(具有正确的名称)。我错过了什么?谢谢!
2 个解决方案
#1
53
Use drop=FALSE
使用drop = FALSE
> x <- df[,1, drop=FALSE]
> x
A
1 10
2 20
3 30
From the documentation (see ?"["
) you can find:
从文档(参见?“[”),您可以找到:
If drop=TRUE the result is coerced to the lowest possible dimension.
如果drop = TRUE,则结果被强制转换为可能的最低维度。
#2
19
Omit the ,
:
省略,:
x <- df[1]
A
1 10
2 20
3 30
From the help page of ?"["
:
从帮助页面?“[”:
Indexing by [ is similar to atomic vectors and selects a list of the specified element(s).
索引[类似于原子向量并选择指定元素的列表。
A data frame is a list. The columns are its elements.
数据框是一个列表。列是它的元素。
#1
53
Use drop=FALSE
使用drop = FALSE
> x <- df[,1, drop=FALSE]
> x
A
1 10
2 20
3 30
From the documentation (see ?"["
) you can find:
从文档(参见?“[”),您可以找到:
If drop=TRUE the result is coerced to the lowest possible dimension.
如果drop = TRUE,则结果被强制转换为可能的最低维度。
#2
19
Omit the ,
:
省略,:
x <- df[1]
A
1 10
2 20
3 30
From the help page of ?"["
:
从帮助页面?“[”:
Indexing by [ is similar to atomic vectors and selects a list of the specified element(s).
索引[类似于原子向量并选择指定元素的列表。
A data frame is a list. The columns are its elements.
数据框是一个列表。列是它的元素。