简体   繁体   English

R 中的元素子集

[英]Element-wise subsetting in R

I am trying to print specific observations from a data frame.我正在尝试从数据框中打印特定的观察结果。 Consider this simple example:考虑这个简单的例子:

df <- data.frame(ID = c(1,1,1,2,2,2,3,3),
                 Week = c(1,2,2,1,1,2,1,1),
                 Y = c(4,2,6,7,5,3,1,9))

I would like to (only) print the rows where (ID = 1 & Week = 2), (ID = 2 & Week = 1) as well as (ID = 3 & Week = 1), giving this output:我想(仅)打印(ID = 1 & Week = 2)、(ID = 2 & Week = 1)以及(ID = 3 & Week = 1)的行,给出这个 output:

rbind(df[(df$ID == 1) & (df$Week == 2),],
      df[(df$ID == 2) & (df$Week == 1),],
      df[(df$ID == 3) & (df$Week == 1),])

The values to be used for indexing are stored in a vector for each variable:用于索引的值存储在每个变量的向量中:

IDidx <- c(1,2,3)
Weekidx <- c(2,1,1)

Is there any solution that takes these vectors and indexes element-wise from them as I have done it "manually" using rbind()?是否有任何解决方案可以像我使用 rbind()“手动”那样从它们中获取这些向量和索引?

Thanks for your help!谢谢你的帮助!

We can create a data frame based on IDidx and Weekidx , and then use the semi_join from the dplyr package.我们可以基于IDidxWeekidx创建一个数据框,然后使用semi_join package 中的dplyr

inx <- data.frame(ID = IDidx, Week = Weekidx)

library(dplyr)

df %>% semi_join(inx, by = c("ID", "Week"))
#   ID Week Y
# 1  1    2 2
# 2  1    2 6
# 3  2    1 7
# 4  2    1 5
# 5  3    1 1
# 6  3    1 9

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

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