[英]Generating a new variable in R where the nth observation depends on the n-1th observation of another column
假设我有一个看起来像这样的数据框:
>df
city year ceep
1 1 1
1 2 1
1 3 0
1 4 1
1 5 0
2 1 0
2 2 1
2 3 1
2 4 0
2 5 1
3 1 1
3 2 0
3 3 1
3 4 0
3 5 1
现在我想创建一个新变量'veep',它取决于不同行中'city'和'ceep'的值。 例如,
veep=1 if ceep[_n-1]=1 & city=city[_n-1]
veep=1 if ceep[_n+2]=1 & ceep[_n+3]=1 & city=city[_n+3]
其中n
是观察行。 我不确定如何将这些条件转换为R语言。 我猜我遇到麻烦的地方是选择一排观察。 我正在考虑一个代码:
df$veep[df$ceep(of the n-1th observation)==1 & city==city(n-1th observ.)] <- 1
df$veep[df$ceep(of the n+2th observation)==1 & df$ceep(of the n+3th observation)==1 &
city==city(n+3th observ.)] <- 1
#note: what's in parentheses is just to demonstrate where I'm having trouble
任何人都可以提供帮助吗?
这是一种写出逻辑步骤的方法。 注意使用idx
来索引向量。 这对于避免超出范围的索引是必要的。
idx <- seq_len(nrow(df))
# Set a default value for the new variable
df$veep <- NA
您的第一组逻辑条件不能应用于df
的第一行,因为索引n - 1
将为0
,并且这不是有效的行索引。 因此,使用tail(*, -1)
来挑选除了veep
和city
的第一个条目之外的所有条目并使用head(*, -1)
来挑选除了ceep
和city
之外的所有ceep
。
df[tail(idx, -1), "veep"] <- ifelse(
head(df$ceep, -1) == 1 &
tail(df$city, -1) == head(df$city, -1),
1, tail(df$veep, -1))
您的下一组标准不能应用于df
的最后三行,因为n + 3
将是无效索引。 所以再次使用head
和tail
功能。 一个棘手的部分是第一个ceep
语句基于n + 2
而不是n + 3
,因此需要head
和tail
的组合。
df[head(idx, -3), "veep"] <- ifelse(
head(tail(df$ceep, -2), -1) == 1 &
tail(df$ceep, -3) == 1 &
head(df$city, -3) == tail(df$city, -3),
1, head(df$veep, -3))
> df$veep
[1] NA 1 1 NA 1 NA NA 1 1 NA NA 1 NA 1 NA
您可以像这样使用for循环
df$veep <- 0
for (i in seq(nrow(df))){
if (i > 1 & i < nrow(df)-2){
if (df[i-1,"ceep"]==1 & df[i-1,"city"] == df[i,"city"])
df[i,"veep"] <- 1
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.