R에서 문자열을 날짜로 변환하는 방법(예제 포함)
날짜 및 시간 데이터를 R로 가져올 때 값을 문자열로 가져오는 경우가 많습니다.
R에서 문자열을 날짜로 변환하는 가장 쉬운 방법은 다음 구문을 사용하는 as.Date() 함수를 사용하는 것입니다.
like.Date(x, 형식)
금:
- x: 단일 문자열 값 또는 문자열 값의 벡터입니다.
- 형식: 날짜에 사용할 형식입니다. 기본값은 YYYY-MM-DD입니다.
R에서 ?strftime 명령을 사용하면 날짜 형식에 사용할 수 있는 인수의 전체 목록을 표시할 수 있지만 가장 일반적인 인수는 다음과 같습니다.
- %d: 해당 월의 일자를 10진수로 표시(01~31)
- %m: 십진수로 표현된 월(01-12)
- %y: 세기가 없는 연도(예: 04)
- %Y: 세기가 포함된 연도(예: 2004)
이 튜토리얼에서는 as.Date() 함수의 실제 사용에 대한 몇 가지 예를 보여줍니다.
예 1: 단일 문자열을 날짜로 변환
다음 코드는 단일 문자열 값을 날짜로 변환하는 방법을 보여줍니다.
#create string value x <- c(" 2021-07-24 ") #convert string to date new <- as.Date(x, format=" %Y-%m-%d ") new [1] "2021-07-24" #check class of new variable class(new) [1] “Date”
예제 2: 문자열 벡터를 날짜로 변환
다음 코드는 문자열 벡터를 날짜로 변환하는 방법을 보여줍니다.
#create vector of strings x <- c(" 2021-07-24 ", " 2021-07-26 ", " 2021-07-30 ") #convert string to date new <- as.Date(x, format=" %Y-%m-%d ") new [1] "2021-07-24" "2021-07-26" "2021-07-30" #check class of new variable class(new) [1] “Date”
예 3: 데이터 프레임 열을 날짜로 변환
다음 코드는 데이터 블록체인 열을 날짜로 변환하는 방법을 보여줍니다.
#create data frame df <- data.frame(day = c(" 2021-07-24 ", " 2021-07-26 ", " 2021-07-30 "), sales=c(22, 25, 28), products=c(3, 6, 7)) #view structure of data frame str(df) 'data.frame': 3 obs. of 3 variables: $ day: Factor w/ 3 levels "2021-07-24","2021-07-26",..: 1 2 3 $ sales: num 22 25 28 $products: num 3 6 7 #convert day variable to date df$day <- as.Date(df$day, format=" %Y-%m-%d ") #view structure of new data frame str(df) 'data.frame': 3 obs. of 3 variables: $day: Date, format: "2021-07-24" "2021-07-26" ... $ sales: num 22 25 28 $products: num 3 6 7
예 4: 여러 날짜 프레임 열을 날짜로 변환
다음 코드는 데이터 블록체인의 여러 열을 날짜로 변환하는 방법을 보여줍니다.
#create data frame df <- data.frame(start = c(" 2021-07-24 ", " 2021-07-26 ", " 2021-07-30 "), end = c(" 2021-07-25 ", " 2021-07-28 ", " 2021-08-02 "), products=c(3, 6, 7)) #view structure of data frame str(df) 'data.frame': 3 obs. of 3 variables: $ start: Factor w/ 3 levels "2021-07-24","2021-07-26",..: 1 2 3 $ end: Factor w/ 3 levels "2021-07-25","2021-07-28",..: 1 2 3 $products: num 3 6 7 #convert start and end variables to date df[,c(' start ', ' end ')] = lapply (df[,c(' start ', ' end ')], function(x) as.Date(x, format=" %Y-%m-%d ")) #view structure of new data frame str(df) 'data.frame': 3 obs. of 3 variables: $start: Date, format: "2021-07-24" "2021-07-26" ... $end: Date, format: "2021-07-25" "2021-07-28" ... $products: num 3 6 7
여기에서 이 예제에 사용된 lapply() 함수에 대해 자세히 알아볼 수 있습니다.
추가 리소스
다음 튜토리얼은 R에서 날짜를 사용하는 방법에 대한 추가 정보를 제공합니다.
R의 날짜 형식에 대한 전체 가이드
R에서 날짜별로 데이터프레임을 정렬하는 방법
R에서 날짜로부터 연도를 추출하는 방법