Summary conditional sum using dplyr [duplicate]

1) pivot_wider We can use pivot_wider like this

library(tidyr)

test %>% 
  pivot_wider(names_from = Year, values_from = count, names_prefix = "count")
## # A tibble: 3 x 4
##   State count2005 count2006 count2007
##   <chr>     <dbl>     <dbl>     <dbl>
## 1 AK        12312      6737         1
## 2 AZ        43243        56         6
## 3 CA         1234       123         8

2) reshape A base R solution using reshape is

reshape(test, dir = "wide", idvar = "State", timevar = "Year")
##   State count.2005 count.2006 count.2007
## 1    AK      12312       6737          1
## 2    AZ      43243         56          6
## 3    CA       1234        123          8

3) xtabs The question seems to want to label the horizontal axis as answer and that can't be done with a data frame. We can do that with a matrix or table but then we will need to put the states into row names rather than a column. If the precise names and dimnames are not important then omit the second line. This also uses only base R.

xt <- xtabs(count ~ State + Year, test)
dimnames(xt) <- list(rownames(xt), answer = paste0("count", colnames(xt)))
xt
##     answer
##      count2005 count2006 count2007
##   AK     12312      6737         1
##   AZ     43243        56         6
##   CA      1234       123         8