我有一个数据帧df,每月降雨量
str(df)
'data.frame': 396 obs. of 21 variables:
$ year : int 1986 1986 1986 1986 1986 1986 1986 1986 1986 1986 ...
$ month : int 1 2 3 4 5 6 7 8 9 10 ...
$ stn1 : int 2 42 91 267 482 1282 1207 982 705 259 ...
$ stn2 : int 0 9 23 61 68 151 196 73 172 59 ...
$ stn3 : int 0 10 34 52 122 258 349 237 140 154 …
我想计算所有站点(stn1,stn2,stn3,....(的降雨异常指数(rai(。 我使用了以下代码:
library(precintcon)
rai(df, granularity = "m")
但是它给出了以下错误
Error: $ operator is invalid for atomic vectors
但是当我只将它用于一个电台时,它可以工作
rai(df[1:3], granularity = "m") #calculating rai for one only station
如何一次计算所有电台的rai而没有任何错误?
rai
函数似乎需要日或月降水序列,因此第一列是固定的。我们可以获取所有以"stn1"
开头的列,并在rai
函数中使用它们。
cols <- grep('^stn1', names(df))
output <- Reduce(function(x, y) merge(x, y, by = c('year', 'month')),
lapply(cols, function(x) precintcon::rai(df[c(1:2, x)], granularity = "m")))
一个解决方案,与@RonakShah提出的解决方案相差不远:
num_stations <- 3
rais <- lapply(1:num_stations, function(k) {
dfk <- df[,c(1,2,k+2)]
rai(dfk, granularity = "m")
})
# Plot rai of the first station
plot(rais[[1]])