r - 根据上面满足条件的第一行改变值

标签 r dplyr

我有数据,其简化版本如下所示:

 df_current <- data.frame(
  start = c('yes', rep('no', 5), 'yes', rep('no', 3)),
  season = c('banana', rep('to update', 5), 'apple', rep('to update', 3)),
  stringsAsFactors = F
)

假设“开始”变量指示新季节开始的时间,我可以将其与日期变量(不包括)结合使用来指示苹果和香蕉季节开始的位置。完成此操作后,我想更新“季节”列中的其余行。当前具有“要更新”值的所有行都应更新为具有最近开始季节的水果类型的值(行按日期排列)。换句话说,我希望数据看起来像这样:

 df_desired <- data.frame(
  start = c('yes', rep('no', 5), 'yes', rep('no', 3)),
  season = c(rep('banana', 6), rep('apple', 4)),
  stringsAsFactors = F
)

我以为类似下面的东西会起作用:

  updated <- df_current %>% 
  rowwise() %>% 
  mutate(season = case_when(
    season != 'to update' ~ season,
    season == 'to update' ~ lag(season)
  ))

但是,这会在所有“要更新”值处生成 NA。

最佳答案

一个简单的方法是将替换 “to update”替换为NA,然后使用fill

library(dplyr)
library(tidyr)

df_current %>%
  mutate(season = replace(season, season == "to update", NA)) %>%
  fill(season)

#   start season
#1    yes banana
#2     no banana
#3     no banana
#4     no banana
#5     no banana
#6     no banana
#7    yes  apple
#8     no  apple
#9     no  apple
#10    no  apple

使用相同的逻辑,您还可以使用 zoo::na.locf 用最新的非缺失值填充缺失值。

关于r - 根据上面满足条件的第一行改变值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57000897/

相关文章:

r - 如何从R中的城市名称和国家获得经纬度坐标?

r - R 中的错​​误 : could not find function . ..

r - 使用 dplyr::select 排列列而不进行硬编码

r - 根据特定行的条件创建一个新变量

R dplyr 滚动总和

r - 如何从 ggplot2 的热图函数中提取多边形?

r - R 中带有权重的直方图

r - 使用 dplyr 过滤数据框

R 脚本计算每 <x> 天的平均值

r - 使用 Dplyr 查找组的最大值并在同一表的另一列中改变结果