2017-03-03 2 views
1

문자열의 문자 벡터가 my_strings인데 일부 요소는 YYYYMMDD 형식의 단일 날짜를 포함합니다. YYYYMMDD 날짜를 MMM YYYY 날짜로 바꾸고 싶습니다. 예를 들어,R 문자열을 사용하여 'YYYYMMDD'를 'MMM YYYY'로 변경하십시오.

my_strings <- c('apple','2000 20150101 bar', '20160228') 

c('apple', '2000 Jan 2015 bar', 'Feb 2016')이됩니다. R (특히 stringr)에서 이것을하는 가장 좋은 방법은 무엇입니까?

나는 다음과 같은 작업 것이라고 생각 :

library(stringr) 
pattern <- '([0-9]{4})([0-9]{2})[0-9]{2}' 
str_replace(my_strings, pattern, str_c(month.abb[as.integer("\\2")], " \\1")) 

하지만 내가 캡처 항목 아무것도 할 수없는 것 같아요? 나는 이것이 작동하는 것을 발견했다 :

library(stringr) 
library(dplyr) 
library(lubridate) 
pattern <- '[0-9]{8}' 
my_strings %>% 
    str_match(pattern) %>% 
    ymd() %>% 
    format('%b %Y') %>% 
    str_replace_na() -> 
    replacement_vals 
str_replace(my_strings, pattern, replacement_vals) 

그러나 이것은 clunky 것처럼 보인다. 더 간단한 접근법이 있어야합니다. 맞습니까? 내 첫 시도 같은 게있어?

답변

4

우리는 gsubfn

library(gsubfn) 
gsubfn("([0-9]{8})", ~format(as.Date(x, "%Y%m%d"), "%b %Y"), my_strings) 
#[1] "apple"    "2000 Jan 2015 bar" "Feb 2016" 
1

기본 R 솔루션이 작업을 수행 할 수 있습니다

my_strings <- c('apple','2000 20150101 bar', '20160228') 

unlist(lapply(strsplit(my_strings, '\ '), function(x) { 
    b1 <- format(as.Date(x, "%Y%m%d"), "%b %Y") 
    x[which(!is.na(b1))] <- na.omit(b1) 
    paste(x, collapse = ' ') 
}) 
) 

# [1] "apple"    "2000 Jan 2015 bar" "Feb 2016"  
관련 문제