2017-10-20 53 views
1

我曾嘗試過幾個此站點上的以前的帖子,但沒有成功。基本上我有形式的數據集:將列中的數據重新整形爲具有測量變量的因子的問題

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 

最後,我需要的是每年爲變量的箱線圖,並能夠在這些年中進行鄧肯測試。如果他們能幫助我,我會爲任何人購買一杯飲料!我之前做過類似的事情,不能爲我的生活找到代碼。

嘗試下面的建議後:

> 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 

回答

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)來製作你想要的劇情了。

+0

如果您使用'group_by(Year)%>%mutate(idx = row_number())'而不是'rownames_to_column()',您將獲得所需的輸出。 –

+0

這給出:%>% + select(「2006」,「2005」,「2004」 ) 錯誤:請提供列名稱' –

+0

如果您使用'dput'提供了正確的數據集,我可以幫助您更好。 – jsb

相關問題