![](/img/trans.png)
[英]How do I loop over a vector of strings and another vector of numbers at the same time in R?
[英]How do I apply this for loop over my character vector and output another vector?
我的代碼的目的是連接向量 v 中的值。為此,我創建了一個帶有兩個 arguments 向量 SID 的 function 連接。 但由於我不明白的原因,
#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]
}
和:
concat(vector = v,
SID = "SV_55tYjKDRKYTRNIh")
當我運行它時,我得到:
Error in concat(vector = v, SID = "SV_55tYjKDRKYTRNIh") :
object 'out' not found
我已經嘗試了其他幾種方法,例如:
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
}
但我遇到了同樣的錯誤。
在 function 中未初始化out
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
}
-測試
> 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
是矢量化的。 所以,循環並不是真正需要的
concat2 <- function(vector,SID){
decrement_append <- "&decrementQuotas=true"
SID_append <- "?surveyId="
paste0(v, SID_append,SID,decrement_append)
}
-測試
> 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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.