R logo

例えば下記データ(Data_c)がある。

X   ID  Cohort  Sex Age ADNC
1   1   232493  LBD     Male    83  Low
2   2   326342  AD      Male    78  High
3   3   326322  LBD     Female  75  Low
4   4   219018  LBD     Male    74  Low
5   5   326217  AD      Male    78  High
6   6   324906  LBD     Male    74  Low
7   7   232973  LBD+AD  Male    83  Intermediate
8   8   297519  LBD+AD  FeMale  84  Intermediate
9   9   210750  LBD     Male    81  Low
10  10  297764  LBD+AD  Male    75  Intermediate

列の抽出

ID, Cohort, Sexの列を抽出したい場合。

dplyr::selectを使って抽出。

select(Data_c, ID, Cohort, Sex)
output
> select(Data_c, ID, Cohort, Sex)
    ID      Cohort  Sex
1   232493  LBD     Male
2   326342  AD      Male
3   326322  LBD     Female
4   219018  LBD     Male
5   326217  AD      Male
6   324906  LBD     Male
7   232973  LBD+AD  Male
8   297519  LBD+AD  FeMale
9   210750  LBD     Male
10  297764  LBD+AD  Male

列の削除

1列目(X)が邪魔なので、これだけ削除したい場合。

dplyr::selectに、メタ文字の「-(◯◯以外)」を組み合わせる。

select(Data_c, ID, Cohort, Sex)
output
> select(Data_c, -X)
    ID      Cohort  Sex Age ADNC
1   232493  LBD     Male    83  Low
2   326342  AD      Male    78  High
3   326322  LBD     Female  75  Low
4   219018  LBD     Male    74  Low
5   326217  AD      Male    78  High
6   324906  LBD     Male    74  Low
7   232973  LBD+AD  Male    83  Intermediate
8   297519  LBD+AD  FeMale  84  Intermediate
9   210750  LBD     Male    81  Low
10  297764  LBD+AD  Male    75  Intermediate

列の並び替え

列を、Age, Sex, それ以外、というふうに並び替える場合、dplyr::selectで、先頭にしたい順に並べ、それ以外を「everything()」で続ける。

Data_c <- select(Data_c, Age, Sex, everything())
output
    Age Sex     X   ID      Cohort  ADNC
1   83  Male    1   232493  LBD     Low
2   78  Male    2   326342  AD      High
3   75  Female  3   326322  LBD     Low
4   74  Male    4   219018  LBD     Not
5   78  Male    5   326217  AD      High
6   74  Male    6   324906  LBD     Low
7   83  Male    7   232973  LBD+AD  Intermediate
8   84  FeMale    8   297519  LBD+AD  Intermediate
9   81  Male    9   210750  LBD     Low
10  75  Male    10  297764  LBD+AD  Intermediate