我想返回数字向量v
中元素的字符串向量,重复的次数与元素的值相同,我必须使用嵌套for循环。
这是我的代码:
ReturnValueTimes <- function(v) {
emptyString <- ""
for(i in 1:length(v)){
for(j in 1:v[i]){
emptyString <- c(emptyString, v[i])
repeatedNumbers <- paste(emptyString, collapse = "")
}
}
return(repeatedNumbers)
}
测试案例:
> ReturnValueTimes(c(2,4,3))
[1] "224444333"
However, I want this to be something like:
> ReturnValueTimes(c(2, 4, 3))
[1] "22" "4444" "333"
> ReturnValueTimes(c(7, 1))
[1] "7777777" "1"
我应该在代码中添加哪些条件(语句)来分隔字符串?或者改变一些东西以获得理想的结果?
答案 0 :(得分:1)
好吧,我不明白为什么你应该为此写一个R函数,因为基础r中已有一个
strrep(x<-c(5,2,3),x)
[1] "55555" "22" "333"
strrep(x<-c(7,4,9),x)
[1] "7777777" "4444" "999999999"
虽然你仍然可以写你的:
ReturnValueTimes=function(x)strrep(x,x)
ReturnValueTimes(c(5,2,3))
[1] "55555" "22" "333"
现在,您可以编写代码:
ReturnValueTimes3 <- function(v) {
store_here=character(length(v))# A character vector which will store
for(i in 1:length(v)){
emptyString <- ""#This is defined inside the first loop in order to rewrite its value after the inner loop is done
for(j in 1:v[i]){
emptyString <- c(emptyString, v[i])
repeatedNumbers <- paste(emptyString, collapse = "")
}
store_here[i] <- repeatedNumbers
}
return(store_here)
}
ReturnValueTimes3(c(3,4,5,6))
[1] "333" "4444" "55555" "666666"
或者你可以这样做:
sapply(c(3,4,5,6),function(x)paste0(rep(x,x),collapse=""))
[1] "333" "4444" "55555" "666666"
如果你想写你的,但要避免明确的for loop
(包括*申请家庭)
ReturnValueTimes2=function(x){
pattern=paste0("(\\d{",x,"})",collapse="")
substitution=paste0("\\",1:length(x),collapse=" ")
vect=paste0(rep(x,x),collapse = "")
strsplit(sub(pattern,substitution,vect)," ")[[1]]
}
ReturnValueTimes2(c(5,3,4,6))
[1] "55555" "333" "4444" "666666"
答案 1 :(得分:0)
使用purrr中的地图功能
library(tidyverse)
ReturnValueTimes <- function (vec) map_chr(vec, function(x) str_c(rep(x, x), collapse = ""))
ReturnValueTimes(c(2, 3, 4))
#> [1] "22" "333" "4444"
由reprex package创建于2018-02-03(v0.1.1.9000)。