我有一个R数据框:
city hour value
0 NY 0 12
1 NY 12 24
2 LA 0 3
3 LA 12 9
我希望针对每个城市,将每行数据除以前一行,并将结果写入新的数据框中。期望的输出如下:
city ratio
NY 2
LA 3
lag
函数获取每个city
的前一个值,将每个value
除以其前一个值,并删除NA
行。library(dplyr)
df %>%
arrange(city, hour) %>%
group_by(city) %>%
summarise(value = value/lag(value)) %>%
na.omit()
# city value
# <chr> <dbl>
#1 LA 3
#2 NY 2
library(data.table)
setDT(df)[order(city, hour), value := value/shift(value), city]
na.omit(df)
您可以像下面这样尝试使用aggregate
聚合函数:
aggregate(value ~city,df, function(x) x[-1]/x[1])
提供
city value
1 LA 3
2 NY 2
数据
> dput(df)
structure(list(city = c("NY", "NY", "LA", "LA"), hour = c(0L,
12L, 0L, 12L), value = c(12L, 24L, 3L, 9L)), class = "data.frame", row.names = c("0",
"1", "2", "3"))