ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [R]함수 paste(), paste0(), outer() 등
    데이터 분석/텍스트 분석 2022. 4. 2. 22:58

    오늘 언급할 함수들은 모두 R의 기본 함수이다.

     

    #nchar()

    벡터의 길이를 확인할 수 있는 함수이다. 길이는 문자열의 경우 공백을 포함하여 길이를 측정한다.

     

       a <- 12342314 
    
       y <- c("We","have","a","dream")
    
       s <- "We have a dream"
    
       nchar(a) # 8
    
       nchar(y) # 2 4 1 5
    
       nchar(s) # 15

    #tolower()

    문자열을 모두 소문자로 만든다.

       y <- c("We","have","a","dream")
    
       s <- "We have a dream"
    
       tolower(y) # "we" "have" "a" "dream"
    
       tolower(s) # "we have a dream"

    #toupper()

    문자열을 모두 대문자로 만든다.

       y <- c("We","have","a","dream")
    
       s <- "We have a dream"
    
      toupper(y) # "WE" "HAVE" "A" "DREAM"
    
      toupper(s) # "WE HAVE A DREAM"

    #paste()

    주어진 벡터들은 연결시켜 문자열을 출력한다. sep 인자를 이용해 연결자를 설정할 수 있고 하나의 벡터에 여러 문자열이 속해있는 경우 collapse 인자를 통해 하나의 문자열로 통합하여 출력할 수 있다.

      paste("Everyone", "wants","to", "fly", sep = "_")
    # "Everyone_wants_to_fly"
      paste("Everyone", "wants", "to", "fly", sep = "")
    # "Everyonewantstofly"
      fox.said <- "what is essential is invisible to the eye"
    
      fox.said.words <- unlist(strsplit(fox.said, split=" "))
    #fox.said.words
    # "what"      "is"        "essential" "is"        "invisible"
    # "to"        "the"       "eye"
    
    #paste(fox.said.words)
    # "what"      "is"        "essential" "is"        "invisible"
    # "to"        "the"       "eye"
    
       paste(fox.said.words, collapse = " ")
    # "what is essential is invisible to the eye"

     

      

    #paste0()

    paste와 기본적인 기능은 같지만 sep의 기본값을 ""로 가진다.

       paste0("Everyone", "wants", "to", "fly")
    # "Everyonewantstofly"

     

    #outer()

    인자로 x, y 숫자 계열의 데이터를 받을 경우 x의 길이의 행 수와 y의 길이의 열 수를 가진 행렬을 만들고 두 데이터의 합을 값으로 가진다. 문자열 벡터를 받을 경우 FUN 인자로 수행할 것을 설정하고 설정한 FUN의 따라 필요한 추가 인자를 설정하여 실행하면 x, y의 길이만큼 행과 열을 만들고 두 데이터에 FUN을 수행한 결괏값을 값으로 가진 행렬을 만든다. 문자열 벡터를 받은 경우 FUN 설정은 필수적이다.

    outer(1:3, 1:3)
    #      [,1] [,2] [,3]
    # [1,]    1    2    3
    # [2,]    2    4    6
    # [3,]    3    6    9
    
    outer(c(2,4,6), c(1,2,3))
    #      [,1] [,2] [,3]
    # [1,]    2    4    6
    # [2,]    4    8   12
    # [3,]    6   12   18
    
    countries <- c("KOR", "US", "EU")
    stat <- c("GDP", "Pop", "Area")
    outer(countries, stat, FUN = paste, sep='-')
    #      [,1]      [,2]      [,3]      
    # [1,] "KOR-GDP" "KOR-Pop" "KOR-Area"
    # [2,] "US-GDP"  "US-Pop"  "US-Area" 
    # [3,] "EU-GDP"  "EU-Pop"  "EU-Area" 
    
    outer(countries, stat)
    # Error in tcrossprod(x, y) : 
    # requires numeric/complex matrix/vector arguments

    댓글

Designed by Tistory.