本文介绍了计算R数据表中前3行的总和(由网格平方)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我想计算每个网格正方形的最后三天的降雨量,并将其添加为我的data.table中的一个新列。要清楚,我想总结当前和上一个两(2)天的降雨量,对于每个仪表网格广场 库(动物园)库(数据表) #制作数据表 rain square desired_result weather< - data.table(rain,square,desired_result)#making the data.table 我尝试回答:此行以前工作,但不再 weather [,rain_3:= filter(rain,rep(1,2),sides = 1),by = list(square)] pre> 这里我尝试另一种方法: #this下一行得到的数字正确,但总和以下值,而不是前面的值。 weather $ rain_3< - rollapply(zoo(weather $ rain),list(seq(-2,0)),sum) #这里我添加的天气$ square ,但仍然没有成功 weather $ rain_3< - rollapply(zoo(weather $ rain),list(seq(-2,0)),sum,by = list(weather $ square)) 我非常感谢您的任何见解或建议。 非常感谢!解决方案 weather [,rain_3:= filter(rain,rep(1,3),sides = 1),by = list(square)] # = 1):#'filter'长于时间序列 weather [,rain_3:= if(.N> 2)filter(rain,rep(1,3),sides = 1) else NA_real_, by = square] #rain square desired_result rain_3 #1:NA 1 NA NA #2:NA 1 NA NA #3:NA 1 NA NA #4:0 1 NA NA #5:0 1 NA NA #6:5 1 5 5 #7:1 1 6 6 #8:0 1 6 6 #9:3 1 4 4 #10:10 2 NA NA 小心dplyr没有加载,因为它掩盖了过滤器。如果你需要dplyr,你可以调用 stats :: filter 显式。 I would like to calculate the rainfall that has fallen over the last three days for each grid square, and add this as a new column in my data.table. To be clear, I want to sum up the current and PREVIOUS two (2) days of rainfall, for each meterological grid squarelibrary ( zoo )library (data.table)# making the data.tablerain <- c(NA, NA, NA, 0, 0, 5, 1, 0, 3, 10) # rainfall values to work withsquare <- c(1,1,1,1,1,1,1,1,1,2) # the geographic grid square for the rainfall measurementdesired_result <- c(NA, NA, NA, NA, NA, 5, 6, 6, 4, NA ) # this is the result I'm looking for (the last NA as we are now on to the first day of the second grid square)weather <- data.table(rain, square, desired_result) # making the data.tableMy attempt to answer: this line used to work, but no longer doesweather[, rain_3 := filter(rain, rep(1, 2), sides = 1), by = list(square)]So here I am trying another method:# this next line gets the numbers right, but sums the following values, not the preceeding ones.weather$rain_3 <- rollapply(zoo(weather$rain), list(seq(-2,0)), sum)# here I add in the by weather$ square, but still no successweather$rain_3 <- rollapply(zoo(weather$rain), list(seq(-2,0)), sum, by= list(weather$square))I would greatly appreciate any insights or suggestions you may have.Many thanks! 解决方案 weather[, rain_3 := filter(rain, rep(1, 3), sides = 1), by = list(square)]#Error in filter(rain, rep(1, 3), sides = 1) :# 'filter' is longer than time seriesweather[, rain_3 := if(.N > 2) filter(rain, rep(1, 3), sides = 1) else NA_real_, by = square]# rain square desired_result rain_3# 1: NA 1 NA NA# 2: NA 1 NA NA# 3: NA 1 NA NA# 4: 0 1 NA NA# 5: 0 1 NA NA# 6: 5 1 5 5# 7: 1 1 6 6# 8: 0 1 6 6# 9: 3 1 4 4#10: 10 2 NA NATake care that dplyr is not loaded because it masks filter. If you need dplyr, you can call stats::filter explicitly. 这篇关于计算R数据表中前3行的总和(由网格平方)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-11 16:29