让我说我有两个向量:
vector1=c("name1","name2","name3")
vector2=c("#DAAD03","#301EE1","#5BD066")
我想遍历两个向量并打印以下行:
vector2[1] <- "#DAAD03" > name1
vector2[2] <- "#301EE1" > name2
vector2[3] <- "#5BD066" > name3
我尝试过:
for (i in vectors1){
number=c(1)
for (j in vectors2{
print ("vectors2[",number,"] <- ",j, ">", i )
number = number+1
}
}
但不起作用。 谢谢您的帮助
我收到以下错误:
> for (i in vectors1){
+ number=c(1)
+ for (j in vectors2{
Erreur : '{' inattendu(e) in:
" number=c(1)
for (j in vectors2{"
> print ("vectors2[",number,"] <- ",j, ">", i )
Error in print.default("vectors2[", number, "] <- ", j, ">", i) :
objet 'j' introuvable
> number = number+1
> }
Erreur : '}' inattendu(e) in " }"
> }
Erreur : '}' inattendu(e) in "}"
>
答案 0 :(得分:1)
for (i in 1:length(vector1)){
cat(paste0("vector2[",i,"] <- ","'",vector2[i],"'"," > ", vector1[i]))
}
vector2[1] <- '#DAAD03' > name1
vector2[2] <- '#301EE1' > name2
vector2[3] <- '#5BD066' > name3
当心多余的循环,如果矩阵/向量大,它们将永远运行。
答案 1 :(得分:0)
我认为您正在寻找这样的东西:
for(i in 1:length(vector1)){
print(paste(vector2[i],">",vector1[i]))}
输出:
[1] "#DAAD03 > name1"
[1] "#301EE1 > name2"
[1] "#5BD066 > name3"
请注意,您也缺少几个括号,并且如果两个向量的长度相同,则不必使用多个循环。