防止单列自动转换为向量 [英] Prevent automatic conversion of single column to vector
问题描述
我有一个这样的数据帧:
df = data.frame(a = 1:3,b = 2:4,c = 3:5)
I have a data frame like this:
df = data.frame(a=1:3, b=2:4, c=3:5)
我正在使用类似于以下内容的方法从该数据框中选择列:
df [,c (T,F,T)]
I am selecting columns from that data frame using something akin to:
df[, c(T, F, T)]
只要至少要返回两列,此方法就可以正常工作;但是,例如,如果我这样做:
df [,c(T,F,F)]
This works fine as long as there are at least two columns to be returned; but, if I do this for example:
df[, c(T, F, F)]
...我突然只得到一个向量,而不是data.frame。
... I suddenly only get a vector instead of a data.frame.
通常这是可以的(甚至是理想的),但是由于以后需要将结果作为data.frame,因此这完全弄乱了我的脚本。
Normally this would be fine (or even desired), but since I need the result to be a data.frame at a later point, this completely messes up my scripts.
有没有办法防止R将这种自动转换为单列选择的向量?
Is there a way I can prevent R from doing this automatic conversion to a vector for single-column selections?
推荐答案
这很简单。追加,将= FALSE
设置为您的子集。
This one is pretty simple. Append , drop = FALSE
to your subsetting.
例如
df [,c(T,F,F),drop = FALSE]
也适用于矩阵。
这篇关于防止单列自动转换为向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!