0

From a frame like this:

df <- data.frame(year = c(2010,2010,2011,2011), stock = c("Amazon","Google","Yahoo","Google")

How can we melt the rows and convert into columns count results? The expected output:

   stock 2010 2011
Amazon     1     0
Google     1     1
Yahoo     0     1
Jim G.
  • 14,600
  • 19
  • 100
  • 158
Nathalie
  • 1,188
  • 3
  • 19

2 Answers2

2
table(rev(df))
#         year
# stock    2010 2011
#   Amazon    1    0
#   Google    1    1
#   Yahoo     0    1

rev() is to have the desired output directly, otherwise transpose with t(table(df)))

Or equivalently:

Aurèle
  • 11,334
  • 1
  • 29
  • 47
1
library(janitor)
df %>% tabyl(stock, year)                 
#>   stock 2010 2011
#>  Amazon    1    0
#>  Google    1    1
#>   Yahoo    0    1
Sam Firke
  • 19,406
  • 8
  • 78
  • 89