Tha*_*Guy 6 regex string split r
我有数据,其中一些项目是由"|"分隔的数字,如:
head(mintimes)
[1] "3121|3151" "1171" "1351|1381" "1050" "" "122"
head(minvalues)
[1] 14 10 11 31 Inf 22
Run Code Online (Sandbox Code Playgroud)
我想要做的是提取所有时间并将它们与最小值匹配.最终结果如下:
times values
3121 14
3151 14
1171 10
1351 11
1381 11
1050 31
122 22
Run Code Online (Sandbox Code Playgroud)
我试过了strsplit(mintimes, "|"),str_extract(mintimes, "[0-9]+")但我尝试过,但似乎没有用.有任何想法吗?
|是一个正则表达元字符.从字面上看,这些特殊字符需要使用[]或使用\\(或者您可以fixed = TRUE在某些函数中使用)进行转义.所以你的电话strsplit()应该是
strsplit(mintimes, "[|]")
Run Code Online (Sandbox Code Playgroud)
要么
strsplit(mintimes, "\\|")
Run Code Online (Sandbox Code Playgroud)
要么
strsplit(mintimes, "|", fixed = TRUE)
Run Code Online (Sandbox Code Playgroud)
关于你的其他stringr功能尝试,str_extract_all()似乎可以做到这一点.
library(stringr)
str_extract_all(mintimes, "[0-9]+")
Run Code Online (Sandbox Code Playgroud)
为了得到你想要的结果,
> mintimes <- c("3121|3151", "1171", "1351|1381", "1050", "", "122")
> minvalues <- c(14, 10, 11, 31, Inf, 22)
> s <- strsplit(mintimes, "[|]")
> data.frame(times = as.numeric(unlist(s)),
values = rep(minvalues, sapply(s, length)))
# times values
# 1 3121 14
# 2 3151 14
# 3 1171 10
# 4 1351 11
# 5 1381 11
# 6 1050 31
# 7 122 22
Run Code Online (Sandbox Code Playgroud)