📌 문자열(Strings)
🎯 base 패키지에 있는 함수
toupper() - 대문자로 변환
tolower() - 소문자로 변환
paste() - 문자열 합치기 구분자로 지정가능
paste0() - 문자열 합치기 공백없이
substr() - 부분 물자열 추출/대체
strsplit()
nchar()
sub() gsub() - 문자열 대체
grep() - * 문자열 검색
string <- "ABCDEFG"
substr(string, 2, nchar(string) - 2)
str_sub("ABCDEFG", -6, -3)
string <- "ABCDEFG"
substr(string, 2, nchar(string) - 2) <- "###"
string
names <- c("허준", "홍길동", "이몽룡", "건국대학교", "과학기술")
names <- ifelse(
nchar(names) == 2,
paste0(substr(names, 1, 1), "#"),
paste0(substr(names, 1, 1), "####", substr(names, nchar(names), nchar(names)))
)
names
sub("a", "A", "abracadabra")
gsub("a", "A", "abracadabra")
animals <- c("tiger", "eagle", "elephant")
sub("e", "E", animals)
gsub("e", "E", animals)
c_animals <- "tiger eagle elephant"
c_animals1 <- gsub(" ", "", c_animals)
c_animals1
strings <- c("Apple", "Tiger", "Cat", "Banana")
grep("a", strings)
grep("a", strings, value = TRUE)
grep("a", strings, ignore.case = TRUE)
grep("a", strings, ignore.case = TRUE, value = TRUE, invert = TRUE)
names <- row.names(mtcars)
names
head(mtcars)
names <- row.names(mtcars)
grep("toyota", names, ignore.case = TRUE, value = TRUE)
🎯 패키지에 있는 함수
str_to_upper()
str_to_lower()
str_c()
str_detect()
str_split()
str_length()
str_detect()
str_extract()
str_trim()
str_sub("20241106", -2, -1)
str_sub("20241106", 5)
str_flatten(c("2024", "11", "06"))
text <- c(" 양쪽 모두 ", " 왼쪽만", "오른쪽만 ", "사이에 스페이스")
print(text)
str_trim(text)
str_trim(text, side = "left")
str_trim(text, side = "right")
addr <- "충북 충주시 충원대로 268"
word(addr, 2)
📌 정규식(Regular Expression)

data <- read_csv("../mydata/도로교통공단_시군구별 월별 교통사고 통계_20231231.csv",
locale = locale(encoding = "CP949"),
show_col_types = FALSE)
head(data)
index <- grep("충북", data$`시도`)
cb <- data[index, ]
cb
table(cb$`시도`)
table(cb$시도)
idx <- grep("시$", cb$`시군구`)
city <- cb[idx, ]
table(city$시군구)
idx <- grep("남", data$`시군구`)
south <- data[idx, ]
table(south$시군구)
idx <- grep("^남", data$`시군구`)
south <- data[idx, ]
table(south$시군구)
idx <- grep("^남.*구$", data$`시군구`)
south <- data[idx, ]
table(south$시군구)
data$시도2 <- paste(data$시도, data$시군구)
idx <- grep("^남.*구$", data$`시군구`)
south3 <- data[idx, ]
table(south3$시도2)