인공지능/R

R - 함수 ① 문자 함수

해피밀세트 2020. 4. 10. 16:27
반응형

 

 

1. nchar : 문자의 수를 리턴하는 함수

# 영문

nchar("R Developer")

nchar("R Developer",type="chars") # 기본값

nchar("R Developer",type="bytes") # 바이트 단위로 세기

# 한글

nchar("빅데이터",type="chars")

nchar("빅데이터",type="bytes")

 

2. strsplit : 부분문자로 분리하는 함수

# 지정한 문자 단위로 분리

strsplit("R Developer",split= " ")

# 한글자씩 분리

strsplit("R Developer",split= character(0))

# 분리된 문자의 타입 및 구조

class(strsplit("R Developer",split= " "))

str(strsplit("R Developer",split= " "))

# 리스트 인덱싱

strsplit("R Developer",split= " ")[[1]][1]

strsplit("R Developer",split= " ")[[1]][2]

unlist(strsplit("R Developer",split= " "))[1]

unlist(strsplit("R Developer",split= " "))[2]

# 벡터 형식으로 바꾸기

unlist(strsplit("R Developer",split= " "))

unlist(strsplit("R Developer",split= ","))

 

3. toupper : 대문자로 리턴

toupper('r developer')

 

4. tolower : 소문자로 리턴

tolower('R DEVELOPER')

 

5. substr : 문자열 추출

  • substr(시작하는 인덱스 번호, 끝 인덱스 번호)

substr("R Developer",1,1)
substr("R Developer",3,3)
substr("R Developer",3,5)

 

6. sub : 첫번째 일치하는 문자만 바꾸는 함수

  • sub(찾아야될 문자, 수정해야될 문자, 대상 문자)
sub('R','Python','R Programmer R Developer')

 

7. gsub : 일치하는 모든 문자를 바꾸는 함수

  • gsub(찾아야될 문자, 수정해야될 문자, 대상 문자)
gsub('R','Python','R Programmer R Developer')

 

8. str_to_title : 첫글자 대문자, 나머지 소문자로 바꾸는 함수

# 라이브러리 stringr 설치
install.packages("stringr")

# stringr 임포트

library(stringr)

str_to_title("r developer")

 

9. regexpr : 지정된 패턴이 처음 등장하는 텍스트 위치

x <- "Learning R is so interesting"
regexpr("ing",x)

# 타입 확인
class(regexpr("ing",x))

# 값만 확인
as.vector(regexpr("ing",x))

# 원하는 값만 보고싶을때 (속성이름을 찾기)
as.vector(attr(regexpr("ing",x),"match.length"))

# 끝점 찾기

begin <- as.vector(regexpr("ing",x))

len <- as.vector(attr(regexpr("ing",x),"match.length"))

end <- begin + len - 1

 

substr(x,begin,end)

substr(strsplit(x,split= ' ')[[1]][1],begin,end)

 

10. gregexpr : 지정된 패턴이 모두 등장하는 텍스트 위치

x <- "Learning R is so interesting"
gregexpr("ing",x)

# 타입 확인

class(gregexpr("ing",x))

# 값만 확인

unlist(gregexpr("ing",x))
as.vector(gregexpr("ing",x)[[1]])

# 끝점 찾기

begin <- as.vector(gregexpr("ing",x)[[1]])
len <- as.vector(attr(gregexpr("ing",x)[[1]],"match.length"))
end <- begin + len - 1

substr(x,begin[1],end[1])
substr(x,begin[2],end[2])

 

반응형

'인공지능 > R' 카테고리의 다른 글

R - 함수 ③ 날짜 함수  (0) 2020.04.10
R - 함수 ② 숫자 함수  (0) 2020.04.10
R - 자료형 ⑥ data.frame(데이터프레임)  (0) 2020.04.09
R - 자료형 ⑤ factor(펙터)  (0) 2020.04.09
R - 자료형 ④ array(배열)  (0) 2020.04.09