将列添加到数据框并在给定条件语句的情况下填充它

时间:2014-06-13 18:07:36

标签: r conditional-statements

我的数据框在结构上看起来像这样但是50000行:

df <- data.frame(X = c(1,2,3,4,1,2,1,2,3,4,5,1,2,3), Y = rnorm(14), Z = c("A","A","A","A","A","A","B","B","B","B","B","B","B","B"))

我希望有一个如下所示的数据框:

df2 <- data.frame(X = c(1,2,3,4,1,2,1,2,3,4,5,1,2,3), Y = rnorm(14), Z = c("A","A","A","A","A","A","B","B","B","B","B","B","B","B"), NEW = c(1,1,1,1,2,2,1,1,1,1,1,2,2,2))

用语言:我有不同的对象(在这种情况下是A,B;列Z)。在每个物体上,在不同位置进行测量,例如, 1,2,3,4发生在位置1的对象A. 1,2发生在位置2的对象A.现在我想添加一个指定位置的列,如df2中的列NEW。

我无法找出可以做到的条件陈述。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

这个怎么样:

df$NEW <- with(df, ave(X, Z, FUN=function(x) cumsum(c(TRUE, x[-1] < x[-length(x)]))))