Programming/R

[ R ] 변수 & 자료형

yul_S2 2022. 11. 14. 11:11
반응형

working directory 설정

  • getwd()
  • setwd()

변수

 

변수이름 명명방법

(1) 변수 이름 명명 규칙 in R
1)  첫 글자는 영문자로 시작
2)  2 번째 단어부터는 숫자, _, . 등을 사용 가능
3)  대문자와 소문자를 구별한다.
4)  변수의 이름은 의미에 맞도록 작성한다.
5) 한 번 정의된 변수는 재사용이 가능하고, 가장 최근의 값이 저장되어 있다.
6)  Camel case 선호

 

ex )'변수.멤버' 형식의 변수 선언

goods.code <- 'a001'
goods.name <- '냉장고'
goods.price <- 850000
goods.des <- '최고 사양, 동급 최고 품질'

 

 

 

(2) 스칼라(scalar)변수
스칼라(scalar)변수: 한 개의 값만 갖는 변수
4벡터(vector)변수: 복수의 자료를 저장할 수 있는 1차원의 선형 자료 구조

 

 

ex ) 벡터 변수 사용

age <- 35
names <- "홍길동"

age
#[1] 35

names
#[1] "홍길동"

 

자료형

R은 변수를 선언할 때 별도의 자료형을 선언하지 않는다.

 

ex ) 스칼라 변수 사용 예

int <- 20
int
# [1] 20

string <- "홍길동"
string
# [1] "홍길동"

boolean <- TRUE
boolean
# [1] TRUE

sum(10, 20, 20)
# [1] 50

sum(10, 20, 20, NA)
# [1] NA

sum(10, 20, 20, NA, na.rm = TRUE)
# [1] 50

ls()
# [1] "age"         "boolean"     "goods.code"  "goods.des"   "goods.name" 
# [6] "goods.price" "int"         "names"       "string"  
  • sum() 함수: 주어진 인수를 이용하여 합계를 구하는 함수
  • option ‘na.rm = T’ :  NA 제거
  • ls() 함수: 현재 메모리에 할당된 변수(객체) 확인하는 함수

 

 

(1) 자료형 확인
is.numeric(), is.logical(), is.character(), is.data.frame(), is.na(), is.integer(), is.double(), is.complex(), is.factor(), is.nan()

 

ex ) 자료형 확인

is.character(string)
# [1] TRUE

x <- is.numeric(int)
x
# [1] TRUE



is.logical(boolean)
# [1] TRUE

is.logical(x)
# [1] TRUE

is.na(x)
# [1] FALS

 

 

(2) 다른 자료형으로 변환하는 함수 

as.numeric(),  as.logical(),  as.character(),  as.data.frame(),  as.list(),  as.array(),  as.integer()., as.double(),. as.complex(), as.factor(), as.vector(), as.Date()

 

ex ) 문자원소를 숫자원소로 형 변환

  • 문자원소
x <- c(1, 2, "3")  
x
# [1] "1" "2" "3"
  • Error
result <- x * 3
Error in x * 3 : non-numeric argument to binary operator
  • 숫자원소
result <- as.numeric(x) * 3   
result
# [1] 3 6 9

c( ) 함수: 벡터(여러 개의 자료를 저장할 수 있는 1차원의 선형 자료구조) 생성

 

 

ex ) 복소수

z <- 5.3 - 3i 
Re(z)
# [1] 5.3

Im(z)
# [1] -3

is.complex(x)
# [1] FALSE

as.complex(5.3)
# [1] 5.3+0i

 

 

 

(3) 자료형과 자료구조 보기

스칼라 변수인 때는 mode()와 class() 결과 동일

ex ) 스칼라 변수의 자료형과 자료구조 확인

mode(int)
# [1] "numeric"

mode(string)
# [1] "character"

mode(boolean)
# [1] "logical"

class(int)
# [1] "numeric"

class(string)
# [1] "character"

class(boolean)
# [1] "logical"

 

 

(4) 요인(Factor)형 변환

  • 요인(Factor): 값의 목록을 범주(category)로 갖는 벡터 자료 
  • Nominal: 범주의 순서는 알파벳 순서로 정렬
  • Ordinal: 범주의 순서는 사용자가 지정한 순서대로 정렬

 

ex ) 문자벡터와 그래프 생성

Error > 문자열 이라서 plot 함수 error

gender <- c("man", "woman", "woman", "man", "man")
plot(gender)
Error in plot.window(...) : 유한한 값들만이 'ylim'에 사용될 수 있습니다
In addition: Warning messages:
1: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by coercion
2: In min(x) : no non-missing arguments to min; returning Inf
3: In max(x) : no non-missing arguments to max; returning -Inf

plot() 함수: 막대그래프 그리기. 숫자 데이터만을 대상으로 그래프 생성 가능.

 

 

ex ) 요인형 변환

  • as.factor(): 요인형 변환 
  • table()함수: 빈도수 계산
Ngender <- as.factor(gender)
table(Ngender)
# Ngender
#  man woman 
 #   3     2 

 

ex ) factor형 변수로 차트 그리기

  • is.factor()함수: 요인형 확인
plot(Ngender)

mode(Ngender)
# [1] "numeric"

class(Ngender)
# [1] "factor"

is.factor(Ngender)
# [1] TRUE

 

 

ex )  factor() 함수를 이용한 Factor형 변환

 

  • factor(): 범주의 순서를 사용자가 지정한 순서대로 정렬하는 기능
  • args(name): 함수의 argument 이름과 관련한 default값 표시
args(factor)
# function (x = character(), levels, labels = levels, exclude = NA, 
#    ordered = is.ordered(x), nmax = NA) 
# NULL

Ogender <- factor(gender, levels = c("woman", "man"), ordered = T)
Ogender
# [1] man   woman woman man   man  
# Levels: woman < man

 

 

ex )  순서가 없는 요인과 순서가 있는 요인형 변수로 차트 그리기

  • par()함수: 그래프 파라미터의 지정

## 한행에두개

par(mfrow = c(1, 2))   
plot(Ngender)
plot(Ogender)

## 두개행 => 한행에 두개

par(mfrow = c(2, 2))
plot(Ngender)
plot(Ogender)

 

 

(4) 날짜형 변환

ex )  날짜형 변환

as.Date("20/02/28", "%y/%m/%d")
# "2020-02-28"

class(as.Date("20/02/28", "%y/%m/%d"))

# "Date"

dates <- c("02/28/20", "02/30/20", "03/01/20")
as.Date(dates, "%m/%d/%y")        # 해당 날짜가 없는 경우 NA

# "2020-02-28" NA           "2020-03-01"
  • as.Date()함수 : 날짜형 변환 / as.Date(변수, format)

 

 

 

ex )  시스템 로케일 정보 확인

Sys.getlocale(category = "LC_ALL")
Sys.getlocale(category = "LC_COLLATE")

 

 

 

 

 

ex )  현재 날짜와 시간 확인

Sys.time()
  • 현재날짜, 시간
  • Sys.time() 함수: 로케일 정보에 따른 현재 날짜와 시간

 

 

 

 

ex )  날짜형 변환

sdate <- "2019-11-11 12:47:5"
class(sdate)
#"character"
  • Strptime()함수 : 날짜형 변환 / Strptime(x,format)

 

as.Date()함수와 strptime()함수는 문자 상수를 날짜형으로 변환할 경우 사용 as.Date()함수는 날짜 자료만 형변환이 가능

 

 

 

 

 

 

ex )  4자리 연도와 2자리 연도 표기

strptime("30-11-2019", format = ("%d-%m-%Y"))
strptime("30-11-19", format = ("%d-%m-%y"))

 

 

 

 

 

반응형