将数据从列重新整形为具有测量变量的因子的问题

时间:2017-10-20 00:32:53

标签: r dataframe reshape

我在此网站上尝试过几个以前的帖子但没有成功。基本上我有一个以下形式的数据集:

Year   Measurement
2006   25.5
2006   19.2
2005   10.3
2005   30.7
2005   15.5
2005   37.1
2004   10.2
2004   19.6
2004   11.7

我需要的地方是:

2006  2005  2004
25.5  10.3  10.2
19.2  30.7  19.6
NA    15.5  11.7
NA    37.1  NA

最终,我需要的是每年变量的盒子图,并且能够在这些年中执行Duncan的测试。如果他们可以帮助我,我会给任何人买一杯饮料!我之前做过类似的事情,并且不能为我的生活找到代码。

尝试以下建议后:

> x <- df %>% 
+   group_by(Year) %>% mutate(idx = row_number())
>   spread(Year) %>% 
+   select("2006", "2005", "2004")
Error: Please supply column name

x的输出表是:

> x
Source: local data frame [1,566 x 3]
Groups: Year [108]

    Year      SO4   idx
   <int>    <dbl> <int>
1   2007 26.34704     1
2   2007 90.44014     2
3   2007 46.90688     3
4   2007 49.58418     4
5   2007 74.22378     5
6   2007 40.61453     6
7   2006 60.19040     1
8   2006 53.03285     2
9   2006 44.14015     3
10  2006 29.36072     4
# ... with 1,556 more rows

1 个答案:

答案 0 :(得分:0)

我认为这就是你想要的:

library(tibble)
library(tidyr)
library(dplyr)

x <- df %>% 
  rownames_to_column() %>% 
  spread(Year, Measurement) %>% 
  select("2006", "2005", "2004")

输出:

#   2006 2005 2004
# 1 25.5   NA   NA
# 2 19.2   NA   NA
# 3   NA 10.3   NA
# 4   NA 30.7   NA
# 5   NA 15.5   NA
# 6   NA 37.1   NA
# 7   NA   NA 10.2
# 8   NA   NA 19.6
# 9   NA   NA 11.7

现在,您可以使用boxplot(x)生成所需的地块。