2017-07-19 49 views
4

我有個月的英語和荷蘭語一個data.frame:從一個字符串變量如何提取並翻譯個月

library(stringr) 
months.english <- month.name 
months.dutch <- c("januari", "februari", "maart", "april", "mei", "juni","juli", "augustus", "september", "oktober", "november", "december") 
months <- data.frame(months.english, months.dutch) 

我也有日期的變量,這在一定程度非結構化和中英文荷蘭:

time <- (c("1 januari 2001", "12 december 2001", "December 9 2001", "2001 maart 13")) 
time <- data.frame(time) 
time$months <- NA 

我要做到以下幾點:在時間data.frame我想了個變量是從日期字符串的一個月,但對於那些在荷蘭的那幾個月裏,我想英語翻譯使得$月的日期等於c(「1月」,「12月」,「12月」,「3月」)。

我該如何做到最快,可能阻止for循環(因爲實際的data.frame有超過100000行)?

回答

3

這是矢量化的stringi方法。

步驟1:提取荷蘭月份名稱:

library(stringi) 
m <- stri_extract_first(tolower(dates$time), 
      regex = paste(months$months.dutch, collapse = "|")) 

步驟2:搭配英語月份名稱:

dates$months <- months$months.english[match(m, months$months.dutch)] 

這應該是非常快的100K行的數據大小。

結果是:

dates 
#    time months 
#1 1 januari 2001 January 
#2 12 december 2001 December 
#3 December 9 2001 December 
#4 2001 maart 13 March 
+0

這真了不起。非常感謝! – hjms

3
library(stringr) 
library(dplyr) 
months.english <- month.name 
months.dutch <- c("januari", "februari", "maart", "april", "mei", "juni","juli", "augustus", "september", "oktober", "november", "december") 
months <- data.frame(months.english, months.dutch) 

mtable <- data_frame(key = c(months.dutch, months.english), 
         months = rep(months.english, 2)) 

time <- (c("1 januari 2001", "12 december 2001", "December 9 2001", "2001 maart 13")) 
time <- data_frame(time) %>% 
    mutate(translate = str_extract(time, "[A-Za-z]+")) %>% 
    left_join(mtable, by = c('translate' = 'key')) 

如果你想使用的tidyverse,你可以創建一個密鑰表加入。

相關問題