R中的LEFT plus FIND函数等价于什么?

我正试图从数据框中的列中提取前几个字符。 我需要的是先遇到一个“,”字符。

数据:

texts 12/5/15, 11:49 - thanks, take care 12/5/15, 11:51 - cool 

我需要的是

 texts date 12/5/15, 11:49 - thanks, take care 12/5/15 12/10/15, 11:51 - cool 12/10/15 

我厌倦了这个,但是这个没有列的东西都回来了

 df$date <- sub(", ", "", df$date, fixed = TRUE) and df$date <- gsub( ".,","", df$texts) 

相当于Excel

 =LEFT(A1, FIND(",",A1,1)-1) 

你可以使用sub

 sub('(^.*?),.*', '\\1', df$texts) # [1] "12/5/15" "12/5/15" 

模式匹配

  • 该行的开头^后面跟着任何字符. 重复零到无限次,但尽可能less*? ,所有被捕获( ... )
  • 紧跟着一个逗号,
  • 随后是任何字符,重复零到无限次.*

这将匹配整条线,并replace它

  • 被俘的群体\\1

其他选项: substrstrsplitstringr::str_extract

如果你打算使用这些date, as.Date (或者strptime ,如果你想要这个时间的话)实际上可以strptime它所需要的东西:

 as.Date(df$texts, '%m/%d/%y')` # or '%d/%m/%y', if that's the format # [1] "2015-12-05" "2015-12-05" 

数据:

 df <- structure(list(texts = structure(1:2, .Label = c("12/5/15, 11:49 - thanks, take care", "12/5/15, 11:51 - cool"), class = "factor")), .Names = "texts", class = "data.frame", row.names = c(NA, -2L)) 

为什么不只是,

 sub(',.*', '', df$texts) #[1] "12/5/15" "12/5/15" 

你可以做

 l <- strsplit (df$date, split = ",") 

使用昏迷然后分裂文本

 sapply (l, "[", 1) 

保持第一部分。