简体   繁体   中英

R adding new column with integer + 1 based on row value

I have a dataframe which looks like this

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)

I would like to add a new column which adds an integer value at each TIME == 0 by ID, giving this:

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) 

Basically I want to produce a "count of TIME == 0" for each ID in the new VISITNUM column.

I have thought about creating the VISITNUM column containing 0's first, then possibly using the ifelse function with first condition DF$TIME == 0. What I cannot get around is how to specify integer + 1 if there are several TIME == 0 within each ID.

Any help would be much appreciated.

Sincerily,

ykl

You could use ave to do a operator for each ID and cumsum to count the numbers of zeros, eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM