Tidy rows in one data frame based on a condition

时间:2019-04-23 15:08:33

标签: r dataframe

I have a question in R programming.

I have a data frame in R with the following data:

Country         Year           Population        Bikes         Revenue
Austria          1970             85               NA            NA
Austria          1973             86               NA            NA
AUSTRIA          1970             NA               56           4567
AUSTRIA          1973             NA               54           4390

I want to summarise this data in order to have the following new data:

Country             Year            Population         Bikes      Revenue
Austria             1970               85               56         4567
Austria             1973               86               54         4390

Thus, I need to exclude the repeated years per country and join the Bikes and Revenue columns to the specific year and country.

I would highly appreciate if you could help me with this issue.

Thank you.

1 个答案:

答案 0 :(得分:4)

One dplyr possibility could be:

df %>%
 group_by(Country = toupper(Country), Year) %>%
 summarise_all(list(~ sum(.[!is.na(.)])))

  Country  Year Population Bikes Revenue
  <chr>   <int>      <int> <int>   <int>
1 AUSTRIA  1970         85    56    4567
2 AUSTRIA  1973         86    54    4390

Or a combination of dplyr and tidyr:

df %>%
 group_by(Country = toupper(Country), Year) %>%
 fill(everything(), .direction = "up") %>%
 fill(everything(), .direction = "down") %>%
 distinct()

Or if you for some reasons need to use the country names starting by an uppercase letter:

df %>%
 mutate(Country = tolower(Country),
        Country = paste0(toupper(substr(Country, 1, 1)), substr(Country, 2, nchar(Country)))) %>%
 group_by(Country, Year) %>%
 summarise_all(list(~ sum(.[!is.na(.)])))

  Country  Year Population Bikes Revenue
  <chr>   <int>      <int> <int>   <int>
1 Austria  1970         85    56    4567
2 Austria  1973         86    54    4390