我有一些项目的数据是用“ |”分隔的数字,例如:
head(mintimes)
[1] "3121|3151" "1171" "1351|1381" "1050" "" "122"
head(minvalues)
[1] 14 10 11 31 Inf 22
我想做的就是提取所有时间并将其与最小值匹配。最后得到这样的结果:
times values
3121 14
3151 14
1171 10
1351 11
1381 11
1050 31
122 22
我已经尝试过strsplit(mintimes, "|")
并且尝试过,str_extract(mintimes, "[0-9]+")
但是它们似乎没有用。有任何想法吗?
|
是一个正则表达式元字符。当按字面使用时,这些特殊字符需要与[]
或一起转义\\
(或可以fixed = TRUE
在某些函数中使用)。因此,您的致电strsplit()
应为
strsplit(mintimes, "[|]")
要么
strsplit(mintimes, "\\|")
要么
strsplit(mintimes, "|", fixed = TRUE)
至于您对stringr
函数的其他尝试,str_extract_all()
似乎可以解决问题。
library(stringr)
str_extract_all(mintimes, "[0-9]+")
为了获得理想的结果,
> 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句