2017-10-12 55 views
0

我正在編碼R將我的變量的一部分變爲唯一列

我有這樣一個表:

region;2012;2013;2014;2015 
1;2465;245;2158;645 
2;44;57;687;564 
3;545;784;897;512 
... 

而且我希望把它改造成:

region;value;annee 
1;2465;2012 
1;245;2013 
1;2158;2014 
1;645;2015 
2;44;2012 
... 

你知不知道我該怎麼辦呢?

+0

歡迎來到StackOverflow!請閱讀關於[如何提出一個好問題](http://stackoverflow.com/help/how-to-ask)以及如何給出[可重現的示例]的信息(http://stackoverflow.com/questions/ 5963269)。這會讓其他人更容易幫助你。 – Sotos

+0

第一個表具有所謂的「寬格式」,後者具有「長格式」。搜索這些術語,你會在R中發現大量不同的方法,因爲這個問題經常出現,不同的包裝作者採取不同的方法。試試這個鏈接:https://stackoverflow.com/questions/2185252/reshaping-data-frame-from-wide-to-long-format – Bernhard

+0

非常感謝,你的解釋很長,我在網上找到了答案:) – celianou

回答

2

首先,讀出的數據:

dat <- read.csv2(text = "region;2012;2013;2014;2015 
1;2465;245;2158;645 
2;44;57;687;564 
3;545;784;897;512", 
       check.names = FALSE) 

數據幀CON從包tidyr轉換爲長格式與gather

library(tidyr) 
dat_long <- gather(dat, key = "annee", , -region) 

結果:

region annee value 
1  1 2012 2465 
2  2 2012 44 
3  3 2012 545 
4  1 2013 245 
5  2 2013 57 
6  3 2013 784 
7  1 2014 2158 
8  2 2014 687 
9  3 2014 897 
10  1 2015 645 
11  2 2015 564 
12  3 2015 512 

您也可以產生你的問題的; - 分隔結果:

write.csv2(dat_long, "", row.names = FALSE, quote = FALSE) 

這導致:

region;annee;value 
1;2012;2465 
2;2012;44 
3;2012;545 
1;2013;245 
2;2013;57 
3;2013;784 
1;2014;2158 
2;2014;687 
3;2014;897 
1;2015;645 
2;2015;564 
3;2015;512 
1

一個例子回答問題stion:

olddata_wide 
#> subject sex control cond1 cond2 
#> 1  1 M  7.9 12.3 10.7 
#> 2  2 F  6.3 10.6 11.1 
#> 3  3 F  9.5 13.1 13.8 
#> 4  4 M 11.5 13.4 12.9 

library(tidyr) 

# The arguments to gather(): 
# - data: Data object 
# - key: Name of new key column (made from names of data columns) 
# - value: Name of new value column 
# - ...: Names of source columns that contain values 
# - factor_key: Treat the new key column as a factor (instead of character vector) 
data_long <- gather(olddata_wide, condition, measurement, control:cond2, factor_key=TRUE) 
data_long 
#> subject sex condition measurement 
#> 1  1 M control   7.9 
#> 2  2 F control   6.3 
#> 3  3 F control   9.5 
#> 4  4 M control  11.5 
#> 5  1 M  cond1  12.3 
#> 6  2 F  cond1  10.6 
#> 7  3 F  cond1  13.1 
#> 8  4 M  cond1  13.4 
#> 9  1 M  cond2  10.7 
#> 10  2 F  cond2  11.1 
#> 11  3 F  cond2  13.8 
#> 12  4 M  cond2  12.9 
相關問題