본문 바로가기
R

R ) gather(), spread() 함수 알아보기 피벗, 언피벗 feat. long type, wide type in r

by C.Mond 2022. 4. 15.
728x90
728x90

안녕하세요

 

오늘은 data를 long type, wide type으로 변경하는것에 대해 공부한 것을 기록하려고 합니다.

 

data의 long type은 gather(long type)함수로 실행을 합니다

반대로 wide type은 spread(wide type)함수로 실행을 합니다.

해당 함수는 tidyr패키지에 있습니다.

 

gapminde패키지의 gapminder data set을 사용하려고 합니다.

install.packages("gapminder")
library(gapminder)
gapminder

country는 나라,

continent는 대륙,

year은 년도,

lifeexp는 수명,

pop는 인구,

gdppercap는 1인당 gdp입니다.

 

해당 data는 long type의 data이고 이를이용해 언피벗 (wide type)으로 바꾸어 보겠습니다.

 

spread(data,key,value,fill)의 인자를 갖고 있습니다.

 

data는 long type의 data를 입력합니다.

key는 long type에서 wide type으로 할 column을 정합니다.

value는 wide type을 채울 column을 선택합니다.

fill은 빈칸에 채울 값을 설정합니다.

spread(data=gapminder,key=year,value=pop)

위와 같이 나타남을 알 수 있습니다.

 

이를 gatehr를 이용해 원래의 data로 만들 수 있습니다.

 

gather(data,key,value,...,na.rm)

 

data는 wide type형태의 data

key는 wide type의 column명을 data로 갖는 새로운 column명을 선택

value는 wide type의 data에 대한 새로운 column명을 선택

...은 key와 value에 들어갈 기존 dataframe의 column이 들어갑니다.

na.rm는 column이 NA인 행을 없앱니다.

 

gather(data=test,key=year1,value=pop1,-colnames(test)[1:4],na.rm=T)

위와 같이 입력을 하면 year, pop 값이 원래대로 돌아오게 됩니다.

test2 %>%
arrange(country)

column순서는 다르지만 data는 같음을 볼 수 있습니다.

test2 %>%
relocate(year1,.before=lifeExp) %>%
relocate(pop1,.before=gdpPercap) %>%
arrange(country)

이렇게 column순서를 바꿔주면 앞선 data와 같은 data를 만들 수 있습니다.

728x90
728x90

댓글