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.
  • 15,141
  • 22
  • 103
  • 166
Nathalie
  • 1,228
  • 7
  • 20

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
  • 12,545
  • 1
  • 31
  • 49
1
library(janitor)
df %>% tabyl(stock, year)                 
#>   stock 2010 2011
#>  Amazon    1    0
#>  Google    1    1
#>   Yahoo    0    1
Sam Firke
  • 21,571
  • 9
  • 87
  • 105