简体   繁体   English

如何阻止单变量data.frame成为一个向量?

[英]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: 问题是我需要:

  • to subset using vectors of variable names of different length 使用不同长度的变量名称的向量来子集
  • get 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM