gpt4 book ai didi

r - 字符串在分隔符 : R 处拆分并展开(向量)

转载 作者:行者123 更新时间:2023-12-04 22:30:04 24 4
gpt4 key购买 nike

我有这个向量(它很大) myvec 。我需要在 / 处拆分它们匹配并创建另一个结果向量 resvector 。我怎样才能在 R 中完成这项工作?

myvec<-c("IID:WE:G12D/V/A","GH:SQ:p.R172W/G", "HH:WG:p.S122F/H")

resvector

IID:WE:G12D, IID:WE:G12V,IID:WE:G12A,GH:SQ:p.R172W,GH:SQ:p.R172G,HH:WG:p.S122F,HH:WG:p.S122H

最佳答案

您可以尝试使用@Tensibai 提到的 strsplit:

sp_vec <- strsplit(myvec, "/") # split the element of the vector by "/" : you will get a list where each element is the decomposition (vector) of one element of your vector, according to "/"
ts_vec <- lapply(sp_vec, # for each element of the previous list, do
function(x){
base <- sub("\\w$", "", x[1]) # get the common beginning of the column names (so first item of vector without the last letter)
x[-1] <- paste0(base, x[-1]) # paste this common beginning to the rest of the vector items (so the other letters)
x}) # return the vector
resvector <- unlist(ts_vec) # finally, unlist to get the needed vector

resvector
# [1] "IID:WE:G12D" "IID:WE:G12V" "IID:WE:G12A" "GH:SQ:p.R172W" "GH:SQ:p.R172G" "HH:WG:p.S122F" "HH:WG:p.S122H"

关于r - 字符串在分隔符 : R 处拆分并展开(向量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31532852/

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