我正在尝试使用spread()
函数来使我的data.frame宽,但是我有一些我什至不理解的错误...
我的数据帧的某些部分如下所示:
> df
NO2 Month
1 23 01
2 27 01
3 16 01
4 13 01
5 26 01
6 23 01
7 51 01
8 46 01
9 21 01
10 18 01
11 13 01
12 22 01
13 47 01
14 60 01
15 49 01
16 76 01
17 38 01
18 24 01
19 15 01
20 20 01
21 33 01
22 17 01
23 19 01
24 20 01
25 25 01
26 46 01
27 53 01
28 41 01
29 54 01
30 28 01
31 28 01
32 51 02
33 61 02
34 56 02
35 57 02
36 30 02
37 12 02
38 27 02
39 13 02
40 35 02
41 40 02
42 40 02
43 47 02
44 72 02
45 55 02
46 30 02
47 10 02
48 29 02
49 50 02
50 39 02
51 61 02
52 56 02
53 44 02
54 46 02
55 35 02
56 34 02
57 41 02
58 39 02
59 39 02
60 27 03
61 48 03
62 36 03
63 40 03
64 41 03
65 45 03
66 46 03
67 43 03
68 55 03 (...)
所以简单地说,我有一年中每一天的值,我想传播它们并为每个月使用 boxplot((,以使其更清晰地阅读,但由于我无法事件传播它,我无法以正确的方式显示它
我正在尝试传播并重塑,但有一些错误:
df=data.frame(data)
df$Month=as.numeric(format(data$date,format="%m"))
df=df%>%select(c("NO2","Month"))
df=reshape(df,idvar=c("NO2","Month"),direction="wide",timevar="Month")
warnings() ## here i have first errors (will show them in below)
df=spread(df,Month,NO2) ## have problems here also
df=spread(df,df$Month,df$NO2) ## and here also
我对reshape()
函数的第一个错误是对于每个"月",我都有这样的东西
1: In reshapeWide(data, idvar = idvar, timevar = timevar, ... :
multiple rows match for Month=1: first taken
对于第二个错误,我有这样的东西
Error in eval_tidy(enquo(var), var_env) : object 'Month' not found
第三次尝试我有这个
Error: "var" must evaluate to a single number or a column name, not NULL
有人可以帮助我吗?我不明白,我已经做了点差,这是我第一次接触这个问题。
您可能需要
library(dplyr)
library(tidyr)
df %>%
group_by(Month) %>%
mutate(row = row_number()) %>%
spread(Month, NO2)
这给你这个输出
# row `1` `2` `3`
# <int> <int> <int> <int>
# 1 1 23 51 27
# 2 2 27 61 48
# 3 3 16 56 36
# 4 4 13 57 40
# 5 5 26 30 41
# 6 6 23 12 45
# 7 7 51 27 46
# 8 8 46 13 43
#.....
或
df %>%
group_by(Month) %>%
mutate(row = row_number()) %>%
spread(row, NO2)
这给你这个
# Month `1` `2` `3` `4` `5` `6` `7` `8` ....
# <int> <int> <int> <int> <int> <int> <int> <int> <int> ....
#1 1 23 27 16 13 26 23 51 46 ....
#2 2 51 61 56 57 30 12 27 13 ....
#3 3 27 48 36 40 41 45 46 43 ....
关键是,当我们想要将数据帧从长到宽转换时,我们需要一个唯一标识符。由于原始数据帧中不存在它,我们通过对每个Month
进行分组来创建它,并使用 row_number()
为每一行分配一个新编号。
如果你想用基 R reshape
获得相同的结果,我们可以使用 ave
和 seq_along
作为参数添加相同的唯一标识符FUN
。
df$row <- with(df, ave(NO2, Month, FUN = seq_along))
reshape(df,direction="wide",idvar ="Month", timevar = "row")