我有2个向量:
index <- as.integer(c(3, 5, 7))
sen <- c("first", "second", "third", "fourth", "fifth", "sixth", "seventh")
我想根据每个字符串的索引将其保存在新向量中:
mySen <- vector(mode = "character", length = length(index))
这样
> mySen
[1] "third"
[2] "fifth"
[3] "seventh"
我尝试了嵌套循环,但是它们输出长度为6的索引i和j
for (j in index){
for(i in 1:length(index)){
print(c(i,j))
}
}
[1] 1 3
[1] 2 3
[1] 3 3
[1] 1 5
[1] 2 5
[1] 3 5
[1] 1 7
[1] 2 7
[1] 3 7
我想要索引
1 3
2 5
3 7
最重要的是,我希望我的新向量mySen能够如前所述正确地填充
> mySen
[1] "third"
[2] "fifth"
[3] "seventh"
答案 0 :(得分:1)
您可以将sen
与index
子集
mySen <- sen[index]
mySen
#[1] "third" "fifth" "seventh"