2016-10-08 46 views
1

假设数据:排序行之间数据中的R

a <- c(400,500,600,700,100,600,700,100) 
b <- c(2,2,1,2,2,1,2,1) 
c <- c('NA','R','NA','G','NA','R','NA','G') 
data <- data.frame(a,b,c) 

输出:

a b c 
1 400 2 NA 
2 500 2 R 
3 600 1 NA 
4 700 2 G 
5 100 2 NA 
6 600 1 R 
7 700 2 NA 
8 100 1 G 

可以轻松地子集,如果它是在同一行中:

subset(data, b== '1' & c =='R') 

输出:

a b c 
6 600 1 R 

我的问题是我如何在行之间子集?例如,如果在上面的行中b ='2'时如何找到c ='R'的所有值?

a b c 
2 500 1 R 
6 600 1 R 

回答

2

如何找到上述排的c = 'R'b = '2'所有值?

如何

b2above <- which(data$b == 2) + 1L 
cR <- which(data$c == "R") 
id <- cR[cR %in% b2above] ## or `id <- intersect(cR, b2above)` 
data[id, ] 

# a b c 
#2 500 2 R 
#6 600 1 R 
1

你可以试试这个太:

indices.b <- which(data$b == 2) 
indices.c <- which(data$c == 'R') 
if ((length(indices.b) > 0) && (length(indices.c) > 0)) { # if such rows exist 
    indices <- which((indices.c - 1) %in% indices.b) # check if consecutive rows 
    if(length(indices)>0) data[indices.c[indices],] # if consecutive rows exist 
} 


#  a b c 
# 2 500 2 R 
# 6 600 1 R