我有一个像这样的字符串向量:
x <- c("ermanaric cayce nonwashable climactical outseeing dorr nubble",
"aver unsegregating preprofess lumme noontime triskele",
"riverbank walachian penza",
"schlieren calthrop",
"hutlike paraphyllium unservile chaplainship bordelaise",
"phlogotic strategics jowlier orthopaedic nonprofiteering",
"vizir rudenture shopkeeper",
"interestuarine sardis",
"anthas figuring",
"unphased engle german emporium organometallic didy uneclipsing",
"bronzy conant reballot",
"extrados facinorous acrolithic",
"paralyzation uningratiating enzymatically enuresis",
"unscholastic extemporarily",
"discipleship fossilize summae",
"concretize intercharge palpate gombroon initiatrices",
"intimation progressiveness",
"unpictorialise",
"romanticization",
"wynnewood",
"unmate libratory polysynthetic")
一些元素需要粘贴在一起以形成更长的字符串。我有一个向量列表,其中包含必须粘贴在一起的元素的索引:
indx <- list(c(3, 4), c(7, 8, 9), c(11, 12), c(14, 15), c(17, 18, 19, 20))
也就是说,必须将第 3 个和第 4 个元素粘贴在一起以形成字符串
"riverbank walachian penza schlieren calthrop"
、第 7、第 8 和第 9 个字符串粘贴在一起形成字符串 "vizir rudenture shopkeeper interestuarine sardis anthas figuring"
依此类推( EDIT ),保持其余字符串的顺序相同。生成的字符串向量将如下所示:y <- c("ermanaric cayce nonwashable climactical outseeing dorr nubble",
"aver unsegregating preprofess lumme noontime triskele",
"riverbank walachian penza schlieren calthrop",
"hutlike paraphyllium unservile chaplainship bordelaise",
"phlogotic strategics jowlier orthopaedic nonprofiteering",
"vizir rudenture shopkeeper interestuarine sardis anthas figuring",
"unphased engle german emporium organometallic didy uneclipsing",
"bronzy conant reballot extrados facinorous acrolithic",
"paralyzation uningratiating enzymatically enuresis",
"unscholastic extemporarily discipleship fossilize summae",
"concretize intercharge palpate gombroon initiatrices",
"intimation progressiveness unpictorialise romanticization wynnewood",
"unmate libratory polysynthetic")
我尝试了以下方法但没有成功:
myfun <- function(obj, indx) {
paste(obj)[length(indx)]
}
mapply(myfun, x, m)
有人可以帮忙吗?
最佳答案
事实indx
不包含 x
中每个项目的条目但是您希望每个返回或合并到某个地方会使这更具挑战性。
一种想法是使用 Reduce
连续更新, 使用临时 NA
s 保持与索引号的对应关系。
my.y<-c(na.omit(Reduce(function(s,i)
replace(s,i,c(paste(s[i],collapse=" "),rep(NA,length(i)-1))),indx,x)))
identical(my.y,y)
#> [1] TRUE
匹配所需的输出。
关于R:根据索引列表粘贴一些字符串向量元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32338758/