我想将以下data.frame的DATE传播到列中,并将年份放在行中。我的数据结构是:
> str(df)
'data.frame': 836 obs. of 3 variables:
$ DATE: Date, format: "2014-01-03" "2014-01-04" "2014-01-06" "2014-01-07" ...
$ VALUE : num 1 3 1 1 2 6 1 2 1 1 ...
$ YEAR : chr "2014" "2014" "2014" "2014" ...
spread(df, key=DATE, value=VALUE)
但是我收到错误消息“无效的列规范”。是不是为此传播了正确的功能?
编辑:
> str(dfTest)
'data.frame': 836 obs. of 3 variables:
$ DATE: Date, format: "2015-01-16" "2014-01-06" "2016-07-28" "2016-05-31" ...
$ VALUE : num 2 1 3 1 2 22 5 1 4 2 ...
$ YEAR : int 2015 2014 2016 2016 2016 2016 2017 2016 2015 2014 ...
>
> head(dfTest)
DATE VALUE YEAR
1 2015-01-16 2 2015
2 2014-01-06 1 2014
3 2016-07-28 3 2016
4 2016-05-31 1 2016
5 2016-04-28 2 2016
6 2016-12-23 22 2016
> spread(dfTest, key=dfTest$DATE, value=dfTest$VALUE)
Error: Invalid column specification
答案 0 :(得分:0)
我无法重现你的问题。
library(tidyr)
df <- data.frame(
DATE = c("2014-01-03", "2014-01-04", "2015-01-06", "2015-01-07", "2016-01-03", "2016-01-04", "2017-01-06", "2017-01-07"),
VALUE = c(1, 3, 6, 2, 4, 3, 4, 1),
YEAR = c("2014", "2014", "2015", "2015", "2016", "2016", "2017", "2017")
)
df$DATE <- as.Date(df$DATE)
df$YEAR <- as.character(df$YEAR)
str(df)
spread(df, key = DATE, value = VALUE)
#str(df)
'data.frame': 8 obs. of 3 variables:
$ DATE : Date, format: "2014-01-03" "2014-01-04" "2015-01-06" "2015-01-07" ...
$ VALUE: num 1 3 6 2 4 3 4 1
$ YEAR : chr "2014" "2014" "2015" "2015" ...
#spread(df, key = DATE, value = VALUE)
YEAR 2014-01-03 2014-01-04 2015-01-06 2015-01-07 2016-01-03 2016-01-04 2017-01-06 2017-01-07
1 2014 1 3 NA NA NA NA NA NA
2 2015 NA NA 6 2 NA NA NA NA
3 2016 NA NA NA NA 4 3 NA NA
4 2017 NA NA NA NA NA NA 4 1