我对 R 很陌生,因为我确信从我的问题中会很明显。
我有一个如下所示的数据框 (d):
dput(d[1:24,])
structure(list(year = c(1967, 1967, 1967, 1967, 1967, 1967, 1967,
1967, 1968, 1968, 1968, 1968, 1968, 1968, 1968, 1968, 1968, 1968,
1968, 1968, 1969, 1969, 1969, 1969), month = c(5, 6, 7, 8, 9,
10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4
), temp = c(16.545, 20.2275, 24.9425, 24.704, 21.5625, 20.3833333333333,
18.085, 16.325, 13.725, 13.095, 13.07, 15.2525, 16.4933333333333,
20.64, 23.0375, 22.4766666666667, 21.1975, 20.458, 17.9725, 16.1866666666667,
13.78, 13.155, 12.822, 14.0666666666667), date = structure(c(-976,
-945, -915, -884, -853, -823, -792, -762, -731, -700, -671, -640,
-610, -579, -549, -518, -487, -457, -426, -396, -365, -334, -306,
-275), class = "Date")), .Names = c("year", "month", "temp",
"date"), row.names = c("1", "2", "3", "4", "5", "6", "7", "8",
"9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19",
"20", "21", "22", "23", "24"), class = "data.frame")
由此我找到并存储了每个月的“temp”平均值:
jan <- 13.80588 feb <- 13.31874 mar <- 13.35263 apr <- 14.31068 may <- 17.00249 jun <- 20.55553 jul <- 23.55765 aug <- 24.55040 sep <- 22.56809 oct <- 20.15921 nov <- 17.70971 dec <- 15.41233
从“temp”列中的每个值中,我想从相应月份中减去平均值并将结果添加到新列中,即: if(d$month==1),5]<-c(d $temp - 一月)。如果 nrow month ==1,则从同一行中的 temp 值中减去 jan。
我尝试使用 for 循环来做到这一点:
for (i in 1:nrow(d)){
+ d[which(d$month[i]==1),5]<-c(d$temp[i] - jan)
+ d[which(d$month[i]==2),5]<-c(d$temp[i] - feb)
+ d[which(d$month[i]==3),5]<-c(d$temp[i] - mar)
+ d[which(d$month[i]==4),5]<-c(d$temp[i] - apr)
+ d[which(d$month[i]==5),5]<-c(d$temp[i] - may)
+ d[which(d$month[i]==6),5]<-c(d$temp[i] - jun)
+ d[which(d$month[i]==7),5]<-c(d$temp[i] - jul)
+ d[which(d$month[i]==8),5]<-c(d$temp[i] - aug)
+ d[which(d$month[i]==9),5]<-c(d$temp[i] - sep)
+ d[which(d$month[i]==10),5]<-c(d$temp[i] - oct)
+ d[which(d$month[i]==11),5]<-c(d$temp[i] - nov)
+ d[which(d$month[i]==12),5]<-c(d$temp[i] - dec)
+ }
有 50 个或更多警告(使用 warnings() 查看前 50 个)
这导致为每个但不是相应的临时条目选择正确的月份,R 使用第一行中的临时值进行每个计算。我敢肯定一定有一个更简单的方法!
提前致谢