使用R中的逻辑子集数据帧

时间:2017-01-11 22:01:10

标签: r dataframe subset

我正在尝试在一年中使用逻辑运算符对数据框进行子集化,我想知道为什么以下情况不起作用。

num <- c(11,22,33,44)
day.of.yr <- c(31,32,33,34)

dframe <- data.frame(num,day.of.yr)

  num day.of.yr
1  11        31
2  22        32
3  33        33
4  44        34

target.days <- c(32,34)

# works
test1 <-dframe[(day.of.yr==target.days[1] | day.of.yr==target.days[2]),]

  num day.of.yr
2  22        32
4  44        34

# doesn't work
test2 <- dframe[day.of.yr==target.days,]

  num day.of.yr
4  44        34

当我在真实数据集上尝试时,R也只输出我希望输出的子集,并带有以下警告消息:

Warning message:
In dframe$day.of.yr == target.days :
longer object length is not a multiple of shorter object length

如果有一种基于一列中的值指定数据帧的多行的快捷方式,那将是一件好事。我尝试了几种不同的方法,但还没有运气。

1 个答案:

答案 0 :(得分:1)

使用%in%,如下所示:

subset(dframe, day.of.yr %in% target.days)