๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Programming/R

CSV ํŒŒ์ผ ์ฝ๊ธฐ/์“ฐ๊ธฐ

CSV ํŒŒ์ผ์„ ์ƒ์„ฑํ•œ ๋’ค, ์ด๋ฅผ ํŠน์ • ๊ฒฝ๋กœ์— ์“ฐ๊ณ  ์ฝ๊ธฐ๋ฅผ ์ˆ˜ํ–‰ํ•˜์—ฌ ๋ณด์ž.

 

In:

df_car = mtcars

df_car %>% 
head()

 

Out:

                   mpg cyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

 

โ–ท ์‹คํ—˜ ๋ฐ์ดํ„ฐ๋กœ R์˜ ๋‚ด์žฅ๋˜์–ด ์žˆ๋Š” mtcars ๋ฐ์ดํ„ฐ๋ฅผ ์‚ฌ์šฉํ•  ๊ฒƒ์ด๋‹ค.

 

In:

getwd()

 

Out:

'C:/Users/user/Desktop/Before'

 

โ–ท getwd ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜์—ฌ, ํ˜„์žฌ ์ง€์ •๋œ ๊ฒฝ๋กœ๋ฅผ ํ™•์ธํ•˜์—ฌ๋ณด์ž.

 

In:

new_wd = 'C:/Users/user/Desktop/After'

setwd(new_wd)

getwd()

 

Out:

'C:/Users/user/Desktop/After'

 

โ–ท setwd ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜์—ฌ, new_wd ๋ณ€์ˆ˜์— ํ• ๋‹น๋œ ๊ฒฝ๋กœ ์œ„์น˜๋กœ ๋ฐ”๊ฟจ๋‹ค. getwd ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ํ˜„์žฌ ์ง€์ •๋œ ๊ฒฝ๋กœ์˜ ์œ„์น˜๊ฐ€ ๋ฐ”๋€Œ์—ˆ์Œ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

 

In:

write.csv(df_car, 'df_car.csv', row.names = TRUE)

read.csv(paste0(new_wd, '/df_car.csv')) %>% 
head()

 

Out:

                  X  mpg cyl disp  hp drat    wt  qsec vs am gear carb
1         Mazda RX4 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
2     Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
3        Datsun 710 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
4    Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
5 Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
6           Valiant 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

 

โ–ท write.csv ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ์ฒซ ๋ฒˆ์งธ ์ธ์ž์— ํ• ๋‹น๋œ ๋ฐ์ดํ„ฐํ”„๋ ˆ์ž„์„ ๋‘ ๋ฒˆ์งธ ์ธ์ž์— ํ• ๋‹น๋œ ์ด๋ฆ„์œผ๋กœ ์ €์žฅํ•  ์ˆ˜ ์žˆ๋‹ค. ์ด๋•Œ, row.names ์ธ์ž๋ฅผ ํ†ตํ•ด ๋ฐ์ดํ„ฐํ”„๋ ˆ์ž„์˜ ํ–‰์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ๋”ฐ๋กœ ์ƒˆ๋กœ์šด ์—ด๋กœ ์ถ”๊ฐ€ํ•˜์—ฌ ์ €์žฅํ•  ์ง€๋ฅผ ๊ฒฐ์ •ํ•  ์ˆ˜ ์žˆ๋‹ค. ์œ„์˜ ๊ฒฐ๊ณผ๋Š” ํ–‰์— ๋Œ€ํ•œ ์ •๋ณด๊ฐ€ X ์—ด๋กœ ์ถ”๊ฐ€๋œ ๋ชจ์Šต์ด๋‹ค.

 

โ–ท read.csv ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ์ง€์ •๋œ ๊ฒฝ๋กœ์—์„œ ํŒŒ์ผ์„ ๋ถˆ๋Ÿฌ์˜ฌ ์ˆ˜ ์žˆ๋‹ค.

 

In:

write.csv(df_car, 'df_car.csv', row.names = FALSE)

read.csv(paste0(new_wd, '/df_car.csv')) %>% 
head()

 

Out:

   mpg cyl disp  hp drat    wt  qsec vs am gear carb
1 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
2 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
3 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
4 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
5 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
6 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

 

โ–ท write.csv ํ•จ์ˆ˜์˜ row.names ์ธ์ž์— FALSE๋ฅผ ์ฃผ์–ด, ๊ธฐ์กด df_car ๋ฐ์ดํ„ฐํ”„๋ ˆ์ž„์˜ ํ–‰์— ๋Œ€ํ•œ ์ •๋ณด๊ฐ€ ํฌํ•จ๋˜์ง€ ์•Š์€ ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.