Reputation: 51
Basically, I have a simple two column dataframe, one with degrees of a circle in 10° intervals, and the other with the frequencies of those degrees in a different dataframe.
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
To this
degree freq
0 6863
10 7652
20 2655
...
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 >.>
Upvotes: 1
Views: 75
Reputation: 886938
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
In base R
, we can use aggregate
aggregate(freq ~ degree, transform(df1,
degree = replace(degree, degree == 360, 0)), sum)
Or as @Onyambu commented
aggregate(freq~ degree %% 360,df1,sum)
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))
Upvotes: 6
Reputation: 1159
If I read you question correctly, your df has only one row with 360
. So, the following may be an option too.
# Add the two rows
df$freq[df$degree == 0] <-
df$freq[df$degree == 0] + df$freq[df$degree == 360]
# Delete row
df <- df[ !df$degree==360,]
Upvotes: 1