-1

I have this dataframe:

dt <- structure(list(year = c(2008L, 2008L, 2009L), name = structure(c(1L, 
2L, 1L), .Label = c("stockA", "stockB"), class = "factor")), .Names = c("year", 
"name"), class = "data.frame", row.names = c(NA, -3L))

I would like to produce a new df like this:

year stockA stockB
2008   1      1
2009   1      0

In order to make it I use this:

table(dt)

but it gives me only the stockA and stockB columns. How can I add the column with the years?

Sasak
  • 189
  • 5
  • 15

1 Answers1

-1

We can use dcast

library(data.table)
dcast(setDT(dt), year~name, length)
#    year stockA stockB
#1: 2008      1      1
#2: 2009      1      0
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 5
    Did you read the question carefully? Half of your answer is already present in the question and the other half is a classic reshape from long to wide duplicate imo. – talat Jun 13 '17 at 07:24
  • 4
    And I was saying that `dcast` is a very frequently asked question and definitely a duplicate. – talat Jun 13 '17 at 07:26