简体   繁体   English

如何用R中的因子分类的数据帧值创建向量?

[英]How to create a vector with the values of a data frame classified by factors in R?

I have a data frame with values classified by levels (factors), so I want to create a vector with the values of an specific level, eg 我有一个数据框,其值按级别(因子)分类,因此我想创建一个具有特定级别值的向量,例如

A <- c("Case1", "Case3", "Case2", "Case3", "Case2",
       "Case1", "Case3", "Case2", "Case2", "Case3",
       "Case1", "Case1", "Case3", "Case1", "Case2")
Factors <- factor(A)
Values <- 1:15

DF <- data.frame(Factors, Values)

Values_of_Case1 <- DF$Values... ????

How to create a vector in order to obtain something like: 如何创建向量以获得类似的结果:

print(Values_of_Case1)
[1]  1  6 11 12 14
DF$Values[DF$Factors == "Case1"]
[1]  1  6 11 12 14

or 要么

subset(DF, Factors=='Case1')$Values
[1]  1  6 11 12 14

should work. 应该管用。

If you wanted only the row index for the matches you could do: 如果只需要匹配项的行索引,则可以执行以下操作:

which(DF$Factors == "Case1")
[1]  1  6 11 12 14

Which in this case is the same, but it might not be in your use case. 在这种情况下,这是相同的,但在您的用例中可能不一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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