[英]Removing String from the column in R
執行R代碼后,我在dataframe列中得到的值是:
2012 年 7 月 25 日投注
2015 年 6 月 22 日投注
2015 年 4 月 9 日
2016 年 11 月 14 日
我只想要日期,如何從值中刪除“bet”、“be”?
我正在使用以下代碼從文本文檔中提取上述值:
coalesce((substr((stringr::str_match(text, "ISDA Master Agreementd as of (. ) ")[, 2]),1,16)),(substr((stringr::str_match(text, "ISDA)主協議日期為 (. ) ")[, 2]),1,13)))
如果我滑動合並參數,則第 4 個值會被截斷。
我對代碼沒問題,但是在清理時,我應該如何刪除“bet”、“be”?
我離成為正則表達式專家還很遠,但這里有一種做你想做的事情的整潔方式:
library(tidyverse, verbose = F)
df <- tibble::tribble(
~V1, ~V2,
1L, "25 July 2012 bet",
2L, "22 June 2015 bet",
3L, "09 April 2015 be",
4L, "14 November 2016"
)
df %>%
mutate(V2 = str_replace(V2, pattern = "[:space:]be.*", replacement = ""))
#> # A tibble: 4 x 2
#> V1 V2
#> <int> <chr>
#> 1 1 25 July 2012
#> 2 2 22 June 2015
#> 3 3 09 April 2015
#> 4 4 14 November 2016
由reprex 包(v0.3.0) 於 2020 年 2 月 21 日創建
我們可以使用sub
刪除空格和所有帶有"be"
sub("\\s+be.*", "", c("25 July 2012 bet", "09 April 2015 be"))
#[1] "25 July 2012" "09 April 2015"
如果您使用lubridate
您可以刪除日期后的多余文本:
library(lubridate)
test_strings <- c("25 July 2012 bet", "09 April 2015 be")
dmy(test_strings)
[1] "2012-07-25" "2015-04-09"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.