How to extract the previous n rows where a certain column value cannot be a particular value?

末鹿安然 提交于 2019-12-11 04:55:17

问题


I've been searching for quite some time now with no luck. Essentially, I'm trying to figure out a way in R to extract the previous n rows where the "LTO Column" is a 0 but starting from where the "LTO Column" is a 1.

Data table:

Week          Price           LTO     
1/1/2019        11              0    
2/1/2019        12              0
3/1/2019        11              0
4/1/2019        11              0
5/1/2019        9.5             1
6/1/2019        10              0
7/1/2019         8              1

Then what I'm trying to do is say if n = 3, starting from 5/1/2019 where LTO = 1. I want to be able to pull the rows 4/1/2019, 3/1/2019. 2/1/2019.

But then for 7/1/2019 where the LTO is also equal to 1, I want to grab the rows 6/1/2019, 4/1/2019, 3/1/2019. In this situation it skips the row 5/1/2019 because is has a 1 in the LTO column.

Any help would be much appreciated.


回答1:


There could be better way to do this , here is one attempt using base R.

#Number of rows to look back
n <- 3

#Find row index where LTO is 1.
inds <- which(df$LTO == 1) 

#Remove row index where LTO is 1
remaining_rows <- setdiff(seq_len(nrow(df)), inds)

#For every inds find the previous n rows from remaining_rows 
#use it to subset from the dataframe and add a new column week2
#with its corresponding date
do.call(rbind, lapply(inds, function(x) {
   o <- match(x - 1, remaining_rows)
   transform(df[remaining_rows[o:(o - (n -1))], ], week2 = df$Week[x])
})) 

#      Week Price LTO    week2
#4  4/1/2019    11   0 5/1/2019
#3  3/1/2019    11   0 5/1/2019
#2  2/1/2019    12   0 5/1/2019
#6  6/1/2019    10   0 7/1/2019
#41 4/1/2019    11   0 7/1/2019
#31 3/1/2019    11   0 7/1/2019

data

df <- structure(list(Week = structure(1:7, .Label = c("1/1/2019", 
"2/1/2019", "3/1/2019", "4/1/2019", "5/1/2019", "6/1/2019", "7/1/2019"), class = 
"factor"), Price = c(11, 12, 11, 11, 9.5, 10, 8), LTO = c(0L, 0L, 0L, 
0L, 1L, 0L, 1L)), class = "data.frame", row.names = c(NA, -7L))


来源:https://stackoverflow.com/questions/56284810/how-to-extract-the-previous-n-rows-where-a-certain-column-value-cannot-be-a-part

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!