请使用dplyr::recode() 和strings::str_remove() 找到这两种解决方案。
我的建议是也学习后者。这样,您将能够学习通过正则表达式转换字符串的更强大的方法。
dplyr::recode() 的解决方案
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
df <- data.frame(duration = c("concentration, up to 2 minutes",
"concentration, up to 4 minutes",
"up to 6 hours"),
name = c("Earth", "Water", "Fire"))
df$duration = recode(df$duration,
"concentration, up to 2 minutes" = "2 minutes",
"concentration, up to 4 minutes" = "4 minutes",
"up to 6 hours" = "6 hours" )
df
#> duration name
#> 1 2 minutes Earth
#> 2 4 minutes Water
#> 3 6 hours Fire
由reprex package (v0.3.0) 于 2020 年 5 月 4 日创建
stringr::str_remove() 的解决方案
library(stringr)
df <- data.frame(duration = c("concentration, up to 2 minutes",
"concentration, up to 4 minutes",
"up to 6 hours"),
name = c("Earth", "Water", "Fire"))
df$duration = str_remove( df$duration, "^.*(?=\\d)")
df
#> duration name
#> 1 2 minutes Earth
#> 2 4 minutes Water
#> 3 6 hours Fire
由reprex package (v0.3.0) 于 2020 年 5 月 4 日创建