R fill in NA with previous row value with condition

自闭症网瘾萝莉.ら 提交于 2019-12-04 12:30:14

问题


I need to fill in NA rows with the previous row value, but only until a criteria is not changed. As a simple example for days of week, meals and prices:

Day = c("Mon", "Tues", "Wed", "Thus", "Fri", "Sat","Sun","Mon", "Tues", 
       "Wed", "Thus", "Fri", "Sat","Sun") 
Meal = c("B","B","B","B","B","D","D","D","D","L","L", "L","L","L") 
Price = c(NA, 20, NA,NA,NA,NA,NA,15,NA,NA,10,10,NA,10) 
df = data.frame(Meal,Day ,Price )
df
   Meal  Day Price
1     B  Mon    NA
2     B Tues    20
3     B  Wed    NA
4     B Thus    NA
5     B  Fri    NA
6     D  Sat    NA
7     D  Sun    NA
8     D  Mon    15
9     D Tues    NA
10    L  Wed    NA
11    L Thus    10
12    L  Fri    10
13    L  Sat    NA
14    L  Sun    10

I need to fill in the NA with the previous but only for the same meal type, over the week.

I have tried

     na.locf(df, fromLast = TRUE)
   Meal  Day Price
1     B  Mon    20
2     B Tues    20
3     B  Wed    15
4     B Thus    15
5     B  Fri    15
6     D  Sat    15
7     D  Sun    15
8     D  Mon    15
9     D Tues    10
10    L  Wed    10
11    L Thus    10
12    L  Fri    10
13    L  Sat    10
14    L  Sun    10

which is wrong as overlaps the meal type. The data should look like this:

  Meal  Day Price
1     B  Mon    20
2     B Tues    20
3     B  Wed    20
4     B Thus    20
5     B  Fri    20
6     D  Sat    15
7     D  Sun    15
8     D  Mon    15
9     D Tues    15
10    L  Wed    10
11    L Thus    10
12    L  Fri    10
13    L  Sat    10
14    L  Sun    10

Many Thanks


回答1:


Another option using data.table

library(data.table)
library(xts)

dt <- data.table(df)

dt[, Price := na.locf(Price, fromLast = TRUE), by = Meal]



回答2:


You could try

library(zoo)
library(dplyr)
df %>% 
     group_by(Meal) %>% 
     mutate(Price= ifelse(any(!is.na(Price)), na.locf(na.locf(Price, 
                    fromLast=TRUE, na.rm=FALSE)), NA_real_))
#     Meal  Day Price
#1     B  Mon    20
#2     B Tues    20
#3     B  Wed    20
#4     B Thus    20
#5     B  Fri    20
#6     D  Sat    15
#7     D  Sun    15
#8     D  Mon    15
#9     D Tues    15
#10    L  Wed    10
#11    L Thus    10
#12    L  Fri    10
#13    L  Sat    10
#14    L  Sun    10


来源:https://stackoverflow.com/questions/29573525/r-fill-in-na-with-previous-row-value-with-condition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!