简体   繁体   中英

Changing Values to Columns and Summarize Rows

I've got this dataframe:

# A tibble: 6 x 3
# Groups:   Entity [3]
  Entity           year count
  <chr>           <dbl> <int>
1 3D SYSTEMS CORP  2019    23
2 3D SYSTEMS CORP  2020     2
3 8X8 INC          2019    74
4 8X8 INC          2020    43
5 AAR CORP         2019    52
6 AAR CORP         2020    18

I want to have the years 2019/2020 as columns and the count as values for the year and entity. And I want to summarize the duplicate entities. The Output should look like this:

# A tibble: 6 x 3
# Groups:   Entity [3]
  Entity           2019  2020
  <chr>           <dbl> <int>
1 3D SYSTEMS CORP    23     2
2 8X8 INC            74    43
3 AAR CORP           52    18

You can do a pivot wider, as @akrun mentioned, like this:

library(tidyverse)

Tibble

Entity <- c("3D SYSTEMS CORP","3D SYSTEMS CORP",
            "8X8 INC","8X8 INC",
            "AAR CORP","AAR CORP")

year <-  c(2019, 2020,
           2019, 2020,
           2019, 2020)

count <-  c(23, 2,
            74, 43,
            52, 18)

tbl<- as_tibble(data.frame(Entity,
                     year,
                     count = as.integer(count)
                     )
                )

Pivot wide or reshape wide from long format

tbl_wide <- 
    tbl %>% 
    pivot_wider(names_from = "year", values_from = "count") 

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