基本上,我有一个简单的两列数据帧,一个以 10° 为间隔的圆度数,另一个在不同的数据帧中具有这些度数的频率。
In the degrees column there is a row for 0° and a row for 360°, and since those mean the same thing (in the context of wind direction) I'd like to combine the two rows into a single 0° row. E.g. from:
degree freq
0 1446
10 7652
20 2655
...
360 5417
Run Code Online (Sandbox Code Playgroud)
To this
degree freq
0 6863
10 7652
20 2655
...
Run Code Online (Sandbox Code Playgroud)
I'm sure this a very simple thing to do but I've spent 3 hours trying to figure it out and have gotten nowhere >.>
One option is to change the value of 360 to 0 and do a group by 'degree' and get the sum of 'freq'
library(dplyr)
df1 %>%
group_by(degree = replace(degree, degree == 360, 0)) %>%
summarise(freq = sum(freq))
# A tibble: 3 x 2
# degree freq
#* <dbl> <int>
#1 0 6863
#2 10 7652
#3 20 2655
Run Code Online (Sandbox Code Playgroud)
In base R, we can use aggregate
aggregate(freq ~ degree, transform(df1,
degree = replace(degree, degree == 360, 0)), sum)
Run Code Online (Sandbox Code Playgroud)
Or as @Onyambu commented
aggregate(freq~ degree %% 360,df1,sum)
Run Code Online (Sandbox Code Playgroud)
NOTE: It is a generalized version where multiple elements with 360 can be changed to 0 and then do a group by sum
df1 <- structure(list(degree = c(0L, 10L, 20L, 360L), freq = c(1446L,
7652L, 2655L, 5417L)), class = "data.frame", row.names = c(NA,
-4L))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
41 次 |
| 最近记录: |