简体   繁体   中英

Use dplyr/tidyr to turn rows into columns in R data frame

I have a data frame like this:

year <-c(floor(runif(100,min=2015, max=2017)))
month <- c(floor(runif(100, min=1, max=13)))
inch <- c(floor(runif(100, min=0, max=10)))
mm <- c(floor(runif(100, min=0, max=100)))
df = data.frame(year, month, inch, mm);

year month inch mm
2016    11    0 10
2015     9    3 34
2016     6    3 33
2015     8    0 77

I only care about the columns year , month , and mm .

I need to re-arrange the data frame so that the first column is the name of the month and the rest of the columns is the value of mm .

Months  2015  2016
Jan     #    #
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec

So two things needs to happen. (1) The month needs to become a string of the first three letters of the month. (2) I need to group by year, and then put the mm values in a column under that year.

So far I have this code, but I can't figure it out:

df %>% 
  select(-inch) %>% 
  group_by(month) %>% 
  summarize(mm = mm) %>% 
  ungroup()

To convert month to names, you can refer to month.abb ; And then you can summarize by year and month, spread to wide format:

library(dplyr)
library(tidyr)
df %>% 
   group_by(year, month = month.abb[month]) %>% 
   summarise(mm = mean(mm)) %>%    # use mean as an example, could also be sum or other 
                                   # intended aggregation methods
   spread(year, mm) %>% 
   arrange(match(month, month.abb))  # rearrange month in chronological order

# A tibble: 12 x 3
#   month   `2015`   `2016`
#   <chr>    <dbl>    <dbl>
# 1   Jan 65.50000 28.14286
# 2   Feb 54.40000 30.00000
# 3   Mar 23.50000 95.00000
# 4   Apr  7.00000 43.60000
# 5   May 45.33333 44.50000
# 6   Jun 70.33333 63.16667
# 7   Jul 72.83333 52.00000
# 8   Aug 53.66667 66.50000
# 9   Sep 51.00000 64.40000
#10   Oct 74.00000 39.66667
#11   Nov 66.20000 58.71429
#12   Dec 38.25000 51.50000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM