Diego Gonzalez Avalos
Diego Gonzalez Avalos

Reputation: 138

How to reshape tables with dplyr in R using years from column

i'm working with R trying to change the shape of one table. For example, in this case, i have the next data:

pet <- c("dog", "cat", "fish", "dog", "cat", "fish", "dog", "cat", "fish")
year <- c("2018", "2018","2018","2019", "2019","2019","2020", "2020","2020")
total <- c("3", "4","10", "5", "2", "3","6","7","8")


animal_store <- data.frame(pet,year,total)

In other view:

   pet year total
1  dog 2018     3
2  cat 2018     4
3 fish 2018    10
4  dog 2019     5
5  cat 2019     2
6 fish 2019     3
7  dog 2020     6
8  cat 2020     7
9 fish 2020     8

I wonder to know how can i get the next table, i tried before with dplyr(), especifically with summarise() but r said there is a problem with my code:

Pet   2018  2019  2020
dog      3     4    10
cat      4     2     7
fish    10     3     8

Any help or another point of view will be appreciated.

Thanks!

Upvotes: 0

Views: 78

Answers (1)

akrun
akrun

Reputation: 887128

If we convert the factor column of 'total' to numeric, xtabs from base R can be used

animal_store$total <- as.numeric(as.character(animal_store$total))
xtabs(total ~ pet + year, animal_store)

Or with tapply

with(animal_store, tapply(total, list(pet, year), FUN = I))
#     2018 2019 2020
#cat     4    2    7
#dog     3    5    6
#fish   10    3    8

In tidyverse, we can use pivot_wider

library(tidyr)
library(dplyr)
animal_store %>% 
     pivot_wider(names_from = year, values_from = total)

Upvotes: 2

Related Questions