R 如何计算下划线的数量,并仅在中间一个上拆分字符串?
我想计算下划线的数量,并在中间下划线处将字符串拆分为两个不同的字符串R 如何计算下划线的数量,并仅在中间一个上拆分字符串?,r,string,R,String,我想计算下划线的数量,并在中间下划线处将字符串拆分为两个不同的字符串 strings <- c('aa_bb_cc_dd_ee_ff', 'cc_hh_ff_zz", "bb_dd") 这里有一个笨拙的解决方案,它假设总是有奇数个下划线 library(stringr) strsplit( strings, paste0("^[^_]*(?:_[^_]*){", str_count(strings, '_') %/% 2, "}\\K_"), perl = TRUE)
strings <- c('aa_bb_cc_dd_ee_ff', 'cc_hh_ff_zz", "bb_dd")
这里有一个笨拙的解决方案,它假设总是有奇数个下划线
library(stringr)
strsplit(
strings,
paste0("^[^_]*(?:_[^_]*){", str_count(strings, '_') %/% 2, "}\\K_"),
perl = TRUE)
# [[1]]
# [1] "aa_bb_cc" "dd_ee_ff"
#
# [[2]]
# [1] "cc_hh" "ff_zz"
#
# [[3]]
# [1] "bb" "dd"
加载库
图书馆长
定义函数
均分
> [[2]]
>[1]cc_hh ff_zz
>
> [[3]]
>[1]bb-dd
由v0.2.1于2019-01-18创建,这里有一个模糊的解决方案,它假设总是有奇数个下划线
library(stringr)
strsplit(
strings,
paste0("^[^_]*(?:_[^_]*){", str_count(strings, '_') %/% 2, "}\\K_"),
perl = TRUE)
# [[1]]
# [1] "aa_bb_cc" "dd_ee_ff"
#
# [[2]]
# [1] "cc_hh" "ff_zz"
#
# [[3]]
# [1] "bb" "dd"
加载库
图书馆长
定义函数
均分
> [[2]]
>[1]cc_hh ff_zz
>
> [[3]]
>[1]bb-dd
由v0.2.1于2019-01-18创建,假设下划线为奇数,且为99或更少
library(stringr)
library(strex)
strings <- c('aa_bb_cc_dd_ee_ff', 'cc_hh_ff_zz', 'bb_dd')
splitMiddleUnderscore <- function(x){
nUnderscore <- str_count(x, '_')
middleUnderscore <- match(nUnderscore, seq(1, 99, 2))
str1 <- str_before_nth(x, '_', middleUnderscore)
str2 <- str_after_nth(x, '_', middleUnderscore)
c(str1, str2)
}
lapply(strings, splitMiddleUnderscore)
#[[1]]
#[1] "aa_bb_cc" "dd_ee_ff"
#[[2]]
#[1] "cc_hh" "ff_zz"
#[[3]]
#[1] "bb" "dd"
这假定下划线为奇数,且为99或更少
library(stringr)
library(strex)
strings <- c('aa_bb_cc_dd_ee_ff', 'cc_hh_ff_zz', 'bb_dd')
splitMiddleUnderscore <- function(x){
nUnderscore <- str_count(x, '_')
middleUnderscore <- match(nUnderscore, seq(1, 99, 2))
str1 <- str_before_nth(x, '_', middleUnderscore)
str2 <- str_after_nth(x, '_', middleUnderscore)
c(str1, str2)
}
lapply(strings, splitMiddleUnderscore)
#[[1]]
#[1] "aa_bb_cc" "dd_ee_ff"
#[[2]]
#[1] "cc_hh" "ff_zz"
#[[3]]
#[1] "bb" "dd"
根据NHAHDH的答案,您需要做的就是添加一个步骤,使用str_count对此处完成的下划线进行计数,并返回下划线的中值
library(stringr)
strsplit(
strings,
paste0("^[^_]*(?:_[^_]*){", str_count(strings, '_') %/% 2, "}\\K_"),
perl = TRUE)
# [[1]]
# [1] "aa_bb_cc" "dd_ee_ff"
#
# [[2]]
# [1] "cc_hh" "ff_zz"
#
# [[3]]
# [1] "bb" "dd"
根据NHAHDH的答案,您需要做的就是添加一个步骤,使用str_count对此处完成的下划线进行计数,并返回下划线的中值
library(stringr)
strsplit(
strings,
paste0("^[^_]*(?:_[^_]*){", str_count(strings, '_') %/% 2, "}\\K_"),
perl = TRUE)
# [[1]]
# [1] "aa_bb_cc" "dd_ee_ff"
#
# [[2]]
# [1] "cc_hh" "ff_zz"
#
# [[3]]
# [1] "bb" "dd"
当有偶数个下划线(例如aa_bb_cc)时发生的情况可能重复?当有偶数个下划线(例如aa_bb_cc)时发生的情况可能重复?您可以使用中间下划线您可以使用中间下划线