我有这个数据框:
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))
我想生成一个像这样的新df:
year stockA stockB
2008 1 1
2009 1 0
为了做到这一点,我用它:
table(dt)
但它只给了我stockA和stockB列。如何添加年份列?
答案 0 :(得分:-1)
我们可以使用dcast
library(data.table)
dcast(setDT(dt), year~name, length)
# year stockA stockB
#1: 2008 1 1
#2: 2009 1 0