我一直在寻找很长一段时间没有运气。本质上,我试图在R中找到一种方法来提取前n行,其中“ LTO列”为0,但从“ LTO列”为1开始。
数据表:
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
然后我想做的是说如果n = 3,从5/1/2019开始,其中LTO =1。我希望能够拉4/1/2019,3/1/2019行。 2019/2/1。
但是然后对于LTO也等于1的7/1/2019,我想获取6/1 / 2019、4 / 1 / 2019、3 / 1/2019行。在这种情况下,它会跳过5/1/2019行,因为LTO列中的行为1。
任何帮助将不胜感激。
答案 0 :(得分:1)
可能有更好的方法,这是尝试使用基数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
数据
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))