gpt4 book ai didi

R提取第n个和第i个分隔符实例之间的字符串

转载 作者:行者123 更新时间:2023-12-04 11:23:11 25 4
gpt4 key购买 nike

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

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) 实例之间的字符串,得到这个:
[1] "90.67.0"  "90.0"     "6.0"      "2"        "24.4.0"   "274.46.0"

或者如果 n = 4 且 i = 5"
[1] "1541" "151"  "A2"   "A"    "A"    "A266"

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

最佳答案

#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个分隔符实例之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44934703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com