R根据行值添加整数+ 1的新列

时间:2014-05-09 09:42:08

标签: r

我有一个看起来像这样的数据框

ID = c("1","1","1","1","1","1","1","2","2","2","2","2","2","2","2","2","2","2","2","2","2") 
TIME = c("0", "0.5", "1","1.5","2","2.5","3","0", "0.5", "1","1.5","2","2.5","3","0", "0.5", "1","1.5","2","2.5","3") 
DF1 = data.frame(ID, TIME)

我想添加一个新列,在每个TIME == 0时按ID添加一个整数值,这样就可以了:

ID = c("1","1","1","1","1","1","1","2","2","2","2","2","2","2","2","2","2","2","2","2","2") 
TIME = c("0", "0.5", "1","1.5","2","2.5","3","0", "0.5", "1","1.5","2","2.5","3","0", "0.5", "1","1.5","2","2.5","3") 
VISITNUM = c("1","1","1","1","1","1","1","1","1","1","1","1","1","1","2","2","2","2","2","2","2")
DF2 = data.frame(ID, TIME, VISITNUM) 

基本上我想为新的VISITNUM列中的每个ID产生“TIME == 0”。

我已经考虑过首先创建包含0的VISITNUM列,然后可能使用ifelse函数,第一个条件为DF $ TIME == 0.我不能解决的是如果有几个TIME ==如何指定整数+ 1每个ID内有0个。

非常感谢任何帮助。

Sincerily,

YKL

1 个答案:

答案 0 :(得分:2)

您可以使用ave为每个ID执行运算符,并使用cumsum计算零的数量,例如:

DF2 <- DF1
## the first argument of ave is the column of interest
## the second (and much more are possible) is the grouping argument
DF2$VISITNUM <- ave(DF1$TIME, DF1$ID, FUN=function(x)cumsum(x == 0))
DF2
#    ID TIME VISITNUM
# 1   1    0        1
# 2   1  0.5        1
# 3   1    1        1
# 4   1  1.5        1
# 5   1    2        1
# 6   1  2.5        1
# 7   1    3        1
# 8   2    0        1
# 9   2  0.5        1
# 10  2    1        1
# 11  2  1.5        1
# 12  2    2        1
# 13  2  2.5        1
# 14  2    3        1
# 15  2    0        2
# 16  2  0.5        2
# 17  2    1        2
# 18  2  1.5        2
# 19  2    2        2
# 20  2  2.5        2
# 21  2    3        2