[英]How to stop single variable data.frame becoming a vector?
When subsetting a data.frame
with asking for only one variable we get a vector. 当
data.frame
询问一个变量来对data.frame
进行子集data.frame
,我们得到一个向量。 This is what we ask for, so it is not strange. 这就是我们要求的,所以这并不奇怪。 However, in other situations (if we ask for more then one column), we get a data.frame object.
但是,在其他情况下(如果我们要求多一列),我们会得到一个data.frame对象。 Example:
例:
> data <- data.frame(a=1:10, b=letters[1:10])
> str(data)
'data.frame': 10 obs. of 2 variables:
$ a: int 1 2 3 4 5 6 7 8 9 10
$ b: Factor w/ 10 levels "a","b","c","d",..: 1 2 3 4 5 6 7 8 9 10
> data <- data[, "b"]
> str(data)
Factor w/ 10 levels "a","b","c","d",..: 1 2 3 4 5 6 7 8 9 10
If I need my data
object not to change it's type from data.frame
no matter if it has only one variable, what do I have to do? 如果我需要我的
data
对象不要从data.frame
更改它的类型,无论它只有一个变量,我该怎么办? The only thing that comes to my mind is: 我唯一想到的是:
data <- data[, "a"]
data <- as.data.frame(data)
...but this seems terribly redundant. ......但这看起来非常多余。 Is there a better way, ie a way of saying "stay a
data.frame
, just give me a certain column"? 有没有更好的方法,即一种说“保留数据
data.frame
,只给我一个专栏”的方式?
The problem is that I need: 问题是我需要:
data.frames
with names unchanged as an output each time. data.frames
。 The best is to use list subsetting. 最好是使用列表子集。 All of these will return a data.frame:
所有这些都将返回data.frame:
data['a']
data[c('a')]
data[c('a', 'b')]
Using matrix subsetting, you would have to add drop = FALSE
: 使用矩阵子集,您必须添加
drop = FALSE
:
data[, 'a', drop = FALSE]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.