2017-08-30 21 views
0

gather関数を使用してデータを整理したいが、複数の列を同時に指定するにはどうすればよいですか?gather()関数で複数の列を指定してデータを整える方法

が、これは私のデータであると言う:

Country Country.Code Year X0tot4 X5tot9 X10tot14 X15tot19 X20tot24 
1 Viet Nam   704 1955 4606 2924  2389  2340  2502 
2 Viet Nam   704 1960 5842 4410  2860  2356  2318 
3 Viet Nam   704 1965 6571 5646  4328  2823  2335 
4 Viet Nam   704 1970 7065 6391  5548  4271  2797 
5 Viet Nam   704 1975 7658 6862  6237  5437  4208 
6 Viet Nam   704 1980 7991 7473  6754  6113  5266 
7 Viet Nam   704 1985 8630 7855  7375  6657  6027 
8 Viet Nam   704 1990 9212 8513  7770  7277  6571 
9 Viet Nam   704 1995 9200 9099  8447  7702  7140 
10 Viet Nam   704 2000 7245 9119  9053  8402  7610 
11 Viet Nam   704 2005 6760 7140  8997  8951  8257 
12 Viet Nam   704 2010 7277 6657  7015  8891  8775 
13 Viet Nam   704 2015 7753 7233  6623  6982  8817 

今、私はX0tot4からX20tot24に変数を持つ1つの新しい列Age.groupsを作成したいです。

df %>% gather(key = "Age.group", value = c(4:8))のようなものです。コンソールはこれが正しい列指定ではないと言っています。しかし、何がありますか?

答えて

3

は、valueは、結果の値列の名前を指定します。を収集する列を指定するには、start_column:end_column構文を使用することができ、これはstart_columnへend_columnからすべての列を収集します。あなたのケースでは、それはX0tot4:X20tot24次のようになります。

df %>% gather(key = 'Age.group', value = 'Value.name', X0tot4:X20tot24) 
#      V      V 
#        V    V 
#         V   V 
#  Country Country.Code Year Age.group Value.name 
#1 Viet Nam   704 1955 X0tot4  4606 
#2 Viet Nam   704 1960 X0tot4  5842 
#3 Viet Nam   704 1965 X0tot4  6571 
#4 Viet Nam   704 1970 X0tot4  7065 
#5 Viet Nam   704 1975 X0tot4  7658 
#6 Viet Nam   704 1980 X0tot4  7991 
#7 Viet Nam   704 1985 X0tot4  8630 
2

Psidomによるニースの回答。また、「 - 」を使用して列を除外することもできます。 gather関数で

df %>% gather(key = "Age.group", value = value, -Country, -Country.Code, -Year) 
1

我々はまた、文字列を照合することによってgatherに列を指定することができます。以下はすべて動作します。

library(tidyverse) 

# Match by the beginning of a string with a pattern 
df %>% gather(Age.group, Value.name, starts_with("X")) 

# Match by if a string containing a pattern 
df %>% gather(Age.group, Value.name, contains("X")) 

# Match by a regular expression pattern 
df %>% gather(Age.group, Value.name, matches("X")) 
関連する問題