본문 바로가기
my_lesson/_R_컴퓨팅

R_컴퓨팅 - 데이터의 입력함수와 출력함수

by boolean 2019. 2. 7.
728x90

R_컴퓨팅 데이터의 입력과 출력

키보드를 통한 데이터의 입력

> v1 = c(1, 2, 3, 4, 5, 6)
>v1
[1] 1 2 3 4 5 6

>v2 = scan()
1:1
2:2 3
4:4 5 6
7:
Read 6 items
>v2
[1] 1 2 3 4 5 6

>v3 = scan(what=" ")            #what = charactor() 와 같은 효과
// what = [double() | integer() | logical() | numeric() | complex() ]
1: A B C
4:
Read 3 items
>v3
[1] "A" "B" "C"


>data1 = data.frame()        # edit()함수를 사용하기 위해 빈 데이터 프레임을 미리 생성한다.

>data1 = edit(data1)

>data1

var1  var2

1    38    A

2    45    D

3    59    G

4    67    B

5    58    C

6    23    E

외부 파일을 통한 데이터 불러오기

>setwd("D:/knou/2-1/R_컴퓨팅")        # 작업폴더 지정 폴더구분 \이 아니고 / 임

>data2_1 = read.table(file="example2_1.txt")

>data2_1 = read.table(file="D:/knou/2-1/R_컴퓨팅/example2_1.txt")  작업폴더 지정 않할 경우

>data2_2 = read.table(file = "example2_2.txt", header=TRUE)  # 헤더가 존재 할경우 첫줄이 헤더임을 명시

>data2_3 = read.table(file = "example2_3.txt", header=TRUE, na.strings="miss")  #결측치miss를 NA로 표시

>data2_4 = read.table(file = "example2_3.txt", header=TRUE, sep=",")  # 구분자가 , 일 경우

>data2_4 = read.csv(file = "example2_3.txt", header=TRUE)    #바로 위의 문장과 같은 결과이다.


>data2_6 = scan(file="example2_3.txt", what=list(Current=0, Innov=0, Loc=""), skip=1, na.strings="none")

각 헤더(변수명) 별로 리스트 형태로 읽어온다.

Current=0    numeric 으로 지정

Innov=0    numeric 으로 지정

Loc=""    character 유형으로 지정

skip=1    첫번째 줄을 건너 뛰어라


>data2_7 = as.data.frame(data2_6)    # 리스트형태로 읽어온 데이터를 데이터 프레임으로 변환한다.

>install.package("xlsx")

>library(xlsx)

>data2_8 = read.xlsx(file="example2_2.xlsx", sheetIndex=1)

sheetIndex=1    Excel문서의 첫번째 워크시트를 열어라는 옵션


>website = "http://www.statsci.org/data/general/auction.txt"
>data2_11 = read.table(website, header=TRUE)

데이터의 출력

>setwd("D:/R files")    # 작업 디렉토리 경로 설정
>sink("output1.txt")    # 피일로 저장 시작
>v1 = c(1, 3, 5, 7, 9, 11, 13, 15, 17, 19, NA)
>mean(v1, na.rm=TRUE)
>sink()     # 피일로 저장 종료

>setwd("D:/R files")    # 작업 디렉토리 경로 설정
>sink("output2.txt")    # 피일로 저장 시작
>source("example1.R", echo=TRUE)    # source파일내의 명령문들을 한번에 수행하고 그 결과를 output2.txt에 저장
>sink()     # 피일로 저장 종료

>setwd("D:/R files")    # 작업 디렉토리 경로 설정
>v1 = c(1, 3, 5, 7, 9)
>v2 = c(2, 4, 6, 8, 10)
>v3 = v1 * v2
>v4 = v1 + v2
>cat("Vector v1 = (", v1,")", "\n", file="output3.txt")
>cat("Vector v2 = (", v2,")", "\n", file="output3.txt", append=TRUE)
>cat("v1 * v2 = (", v3,")", "\n", file = "output3.txt", append=TRUE)
>cat("v1 + v2 = (", v4")", "\n", file = "output3.txt", append=TRUE)
append=TRUE  덧붙여 입력

>setwd"D:/R files")
>write.table(iris, "iris1.txt")    # 기본으로 행 번호 들어감
>write.table(iris, "iris1.txt", row.names = FALSE)    # 행번호 없음
>write.table(iris, "iris1.txt", row.names = FALSE, quote=FALSE)    # 문자열 따옴표 없음
>write.table(iris, "iris1.txt", row.names = FALSE, quote=FALSE, sep="\t")    # 탭으로 분리
>write.table(iris, "iris1.txt", row.names = FALSE, quote=FALSE, sep=",")    # 쉼표로 분리

>install..package(xlsx)
>livrary(xlsx)
>setwd"D:/R files")
>write.xlsx(iris, "iris.xlsx")









댓글