R提取第n个和第i个分隔符实例之间的字符串 [英] R extract string between nth and ith instance of delimiter

查看:30
本文介绍了R提取第n个和第i个分隔符实例之间的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串向量,类似于这个,但有更多的元素:

I have a vector of strings, similar to this one, but with many more elements:

s <- c("CGA-DV-558_T_90.67.0_DV_1541_07", "TC-V-576_T_90.0_DV_151_0", "TCA-DV-X_T_6.0_D_A2_07", "T-V-Z_T_2_D_A_0", "CGA-DV-AW0_T.1_24.4.0_V_A6_7", "ACGA-DV-A4W0_T_274.46.0_DV_A266_07")

我想使用一个函数来提取分隔符_"的第 n 个和第 i 个实例之间的字符串.例如,第 2 个 (n = 2) 和第 3 个 (i = 3) 实例之间的字符串,得到这个:

And I would like to use a function that extracts the string between the nth and ith instances of the delimiter "_". For example, the string between the 2nd (n = 2) and 3rd (i = 3) instances, to get this:

[1] "90.67.0"  "90.0"     "6.0"      "2"        "24.4.0"   "274.46.0"

或者如果 n = 4 且 i = 5"

Or if n = 4 and i = 5"

[1] "1541" "151"  "A2"   "A"    "A"    "A266"

有什么建议吗?感谢您的帮助!

Any suggestions? Thank you for your help!

推荐答案

#FUNCTION
foo = function(x, n, i){
    do.call(c, lapply(x, function(X)
        paste(unlist(strsplit(X, "_"))[(n+1):(i)], collapse = "_")))
}

#USAGE
foo(x = s, n = 3, i = 5)
#[1] "DV_1541" "DV_151"  "D_A2"    "D_A"     "V_A6"    "DV_A266"

这篇关于R提取第n个和第i个分隔符实例之间的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆