Reputation: 381
The intention of my code is to concatenate the values from the vector v. To do this, I created a function concat with two arguments vector, SID. But for reasons I don't understand,
#A character vector to which other strings will be appended
v <- c("R_2wmKOSbPWHl4VtT2","R_2TtslLEVNeHs2r73","R_ZF79IJ60LaxxsuR4","R_3JJDUkrZ07eIwnh5","R_3JrWuv9fsLK6qNx6")
concat <- function(vector,SID){
decrement_append <- "&decrementQuotas=true"
SID_append <- "?surveyId="
for(i in 1:length(vector)){
out[i] <- paste0(v[i],SID_append,SID,decrement_append)
}
out[i]
}
And:
concat(vector = v,
SID = "SV_55tYjKDRKYTRNIh")
When I run this, I get:
Error in concat(vector = v, SID = "SV_55tYjKDRKYTRNIh") :
object 'out' not found
I've tried it a couple of other ways, such as:
concat <- function(vector,SID){
decrement_append <- "&decrementQuotas=true"
SID_append <- "?surveyId="
new_vector <- for(i in 1:length(vector)){
out[i] <- paste0(v[i],SID_append,SID,decrement_append)
}
new_vector
}
But I'm getting the same error.
Upvotes: 1
Views: 1194
Reputation: 886948
The out
is not initialized in the function
concat <- function(vector,SID){
out <- character(length(vector))
decrement_append <- "&decrementQuotas=true"
SID_append <- "?surveyId="
for(i in 1:length(vector)){
out[i] <- paste0(v[i],SID_append,SID,decrement_append)
}
out
}
-testing
> concat(v, "SV_55tYjKDRKYTRNIh")
[1] "R_2wmKOSbPWHl4VtT2?surveyId=SV_55tYjKDRKYTRNIh&decrementQuotas=true" "R_2TtslLEVNeHs2r73?surveyId=SV_55tYjKDRKYTRNIh&decrementQuotas=true"
[3] "R_ZF79IJ60LaxxsuR4?surveyId=SV_55tYjKDRKYTRNIh&decrementQuotas=true" "R_3JJDUkrZ07eIwnh5?surveyId=SV_55tYjKDRKYTRNIh&decrementQuotas=true"
[5] "R_3JrWuv9fsLK6qNx6?surveyId=SV_55tYjKDRKYTRNIh&decrementQuotas=true"
paste/paste0
are vectorized. So, looping is not really needed
concat2 <- function(vector,SID){
decrement_append <- "&decrementQuotas=true"
SID_append <- "?surveyId="
paste0(v, SID_append,SID,decrement_append)
}
-testing
> concat2(v, "SV_55tYjKDRKYTRNIh")
[1] "R_2wmKOSbPWHl4VtT2?surveyId=SV_55tYjKDRKYTRNIh&decrementQuotas=true" "R_2TtslLEVNeHs2r73?surveyId=SV_55tYjKDRKYTRNIh&decrementQuotas=true"
[3] "R_ZF79IJ60LaxxsuR4?surveyId=SV_55tYjKDRKYTRNIh&decrementQuotas=true" "R_3JJDUkrZ07eIwnh5?surveyId=SV_55tYjKDRKYTRNIh&decrementQuotas=true"
[5] "R_3JrWuv9fsLK6qNx6?surveyId=SV_55tYjKDRKYTRNIh&decrementQuotas=true"
Upvotes: 2