gpt4 book ai didi

R 用前一行值填充 NA 和条件

转载 作者:行者123 更新时间:2023-12-04 10:33:08 24 4
gpt4 key购买 nike

我需要用前一行值填充 NA 行,但仅在条件未更改之前。
作为一周中的几天、膳食和价格的简单示例:

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

我需要在 NA 中填写上一个但仅适用于相同膳食类型的一周。

我试过了
     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

这是错误的,因为与膳食类型重叠。
数据应如下所示:
  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

非常感谢

最佳答案

使用 data.table 的另一种选择

library(data.table)
library(xts)

dt <- data.table(df)

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

关于R 用前一行值填充 NA 和条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29573525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com