我想以其他列中的值为基础替换前一行中的值。
这是我的数据示例,其中包含在各种活动中花费的分钟/天。
activity <- c("car","soccer","eat","drink")
category <- c("travel","sport","eat/drink","eat/drink")
duration <- c(75,15,10,160)
df <- data.frame(activity, category,duration)
activity category duration
1 car travel 75
2 soccer sport 15
3 eat eat/drink 10
4 drink eat/drink 160
如果在任何一行中,“饮酒”的持续时间是> 5分钟(因为它在第4行),我想用5分钟替换该行中的“持续时间”,并将剩余时间(在这种情况下为155分钟)添加到前一行中的“持续时间”值,除非前一行有“吃/喝”作为其“类别”,在这种情况下,我想将剩余时间添加到前一行之前的行的“持续时间”......
在上面的例子中,我会在第2行添加155分钟到“持续时间”。但是,如果第2行也有“吃/喝”作为其“类别”,我想要将155分钟添加到前一个行(第1行)。
感谢您的帮助!
到目前为止,我已经尝试过:
df$duration[-nrow(df)] <- ifelse(df$activity[-1]=="drink" & df$duration[-1] > 5,
df$duration + c(df$duration[-1]-5, 0),
df$duration)
将155分钟添加到上一行,并给我这个:
activity category duration
1 car travel 75
2 soccer sport 15
3 eat eat/drink 165
4 drink eat/drink 160
然后我只用5分钟替换了第4行的持续时间,就像这样。
df$duration <- ifelse(df$activity =="drink" & df$duration >5,
5,
df$duration)
给了我这个......
activity category duration
1 car travel 75
2 soccer sport 15
3 eat eat/drink 165
4 drink eat/drink 5
但我无法弄清楚如何将155分钟移动到前一行(第2行),条件是它没有“吃/喝”作为类别。在那种情况下,我想把它移到前面等等......
答案 0 :(得分:0)
这是一个答案,但不幸的是我没有设法进行模糊连接,暗示左侧有一列,右侧有两列。所以在某个时刻(合并时)会有笛卡尔积。你的结果是'df6',变量'duration2'。
activity <- c("car","soccer","eat","drink","car","drink","car","drink")
category <- c("travel","sport","eat/drink","eat/drink","travel","eat/drink","travel","eat/drink")
duration <- c(75,15,10,160,100,50,200,60)
df <- data.frame(activity, category,duration)
df$row<-1:nrow(df)
df1<-df[(activity=="drink")&(duration>5),]
df1$time<-df1$duration-5
library(dplyr)
df2<- df1
df2$row1<-lag(df2$row)
df2<-rename(df2,row2=row)
df$key <-1
df2$key <-1
df3 <- merge(df,df2,by="key") %>% filter(((is.na(row1)&(row<row2)|(row>row1)&(row<row2)))&(category.x!="eat/drink"))
df4 <- df3 %>% group_by(row1) %>%
summarize(row=last(row),time=last(time)) %>% select(row,time)
df5 <- df %>% left_join(df4,by="row") %>%
mutate(duration2=ifelse(is.na(time),duration,duration+time)) %>%
select(activity,category,duration,duration2,row)
df2 <- select(df2,row2,time)
df6 <- df5 %>% left_join(df2,by=c("row" = "row2")) %>%
mutate(duration2=ifelse(is.na(time),duration2,duration-time)) %>%
select(-time)
df6
# activity category duration duration2 row
#1 car travel 75 75 1
#2 soccer sport 15 170 2
#3 eat eat/drink 10 10 3
#4 drink eat/drink 160 5 4
#5 car travel 100 145 5
#6 drink eat/drink 50 5 6
#7 car travel 200 255 7
#8 drink eat/drink 60 5 8