【发布时间】:2014-07-19 09:57:14
【问题描述】:
我正在尝试根据一个因素对数据框进行子集化。然而,即使在子集 R 显示其他因素之后。
例如,在 R 中包含的 iris 数据集中,我想创建一个仅包含 Setosa 物种的子集。然而,即使在子集 R 显示浏览数据时有 3 个因素仅显示 Setosa 之后。这是为什么呢?
提前致谢
#Load Data
library(datasets)
data(iris)
#Subset specie into new data frame only containing Setosa oberservations
sub = iris[iris$Species == "setosa",]
#View sub data frame. Why are there still three levels?
str(sub)
'data.frame': 50 obs. of 5 variables:
$ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
$ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
$ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
$ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
$ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
【问题讨论】:
-
使用
sub <- subset(iris, iris$Species == "setosa")会不会更方便? -
我想可能是这样。我是 R 新手,所以我不熟悉所有各种功能。感谢您的提示
-
您实际上并没有创建新数据,因此它仍然保持
iris的属性,因为它只是较大数据结构中的一小块。在sub中,您可以通过sub$Species <- as.character(sub$Species)将其更改为字符。 -
另见this问题;这对我来说是一个折腾,这应该是一个副本。
-
回复我的评论:在意识到
droplevels()可用后,在这种情况下这将是更好的功能。 @joran,不错的发现。尤其是评论里的那个。非常有用的信息。