Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

r - Create new rows and put a flag to differentiate between existing row

I have a dataset like this:

df_have <- data.frame(id = rep("a",3), time = c(1,3,5), flag = c(0,1,1))

The data has one row per time per id but I need to have the second row duplicated and put into the data.frame like this:

df_want <- data.frame(id = rep("a",4), time = c(1,3,3,5), flag = c(0,0,1,1))

The flag variables should become 0 with the new row added and all other information the same. Any help would be appreciated.

Edit: The comments below are helpful but I would also need to do this in groups by id and some ids have more rows than other ids. After reading this and seeing the comments below I see the logic isn't clear. My original data does not have a count variable (what I call flag) but it needs it in the final output. What I would need is that every row besides for the first and last timepoint (within each id) to be duplicated and every time there is a duplicate make a counter to demonstrate when a row was created until the next new row is created.

df_have2 <- data.frame(id = c(rep("a",3),rep("b",4))  , 
                      time = c(1,3,5,1,3,5,7))


df_want2 <- data.frame(id = c(rep("a",4),rep("b",6)),
                       time = c(1,3,3,5,1,3,3,5,5,7),
                       flag = c(1,1,2,2,1,1,2,2,3,3))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

We could expand the data with slice and then create the 'flag' by matching the 'time' with unique values of 'time' and take the lag of it

library(dplyr)
df_have2 %>% 
     group_by(id) %>% 
     slice(rep(row_number(), c(1, rep(2, n() - 2), 1))) %>%
     mutate(flag = lag(match(time, unique(time)),  default = 1)) %>% 
     ungroup
# A tibble: 10 x 3
#   id     time  flag
#   <chr> <dbl> <dbl>
# 1 a         1     1
# 2 a         3     1
# 3 a         3     2
# 4 a         5     2
# 5 b         1     1
# 6 b         3     1
# 7 b         3     2
# 8 b         5     2
# 9 b         5     3
#10 b         7     3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...