迭代向量中的值

时间:2015-08-01 13:12:58

标签: r

我尝试迭代一个向量来创建一组名称。因此,我会做以下事情:

load <- function() {

#create empty vector for storing website adresses
vector_sites <- c()  
names <- c("lening", "krediet")

for (name in names(names)){
adress_part1 <- "https://www.google.com/trends/explore#q="
adress_part2 <- names[i]
adress_part3 <- "&geo=NL&date=today%203-m&cmpt=q&tz=Etc%2FGMT-2"

total_adress <- paste(adress_part1, adress_part2, adress_part3, sep="")
print(names[i])
vector_sites <- append(vector_sites, total_adress)

}

但这似乎不起作用。关于我哪里出错的任何想法?

2 个答案:

答案 0 :(得分:1)

正如@akrun所说,你可以简单地使用paste0(adress_part1, names, adress_part3)。要使代码工作,您需要以下内容:

load <- function() {

    vector_sites <- c()  
    names <- c("lening", "krediet")

    for (i in seq_along(names)) {
        adress_part1 <- "https://www.google.com/trends/explore#q="
        adress_part2 <- names[i]
        adress_part3 <- "&geo=NL&date=today%203-m&cmpt=q&tz=Etc%2FGMT-2"

        total_adress <- paste0(adress_part1, adress_part2, adress_part3)
        print(names[i])
        vector_sites <- append(vector_sites, total_adress)
    }
    return(vector_sites)
}

我为此添加了一个return语句。

答案 1 :(得分:1)

@ jeff的回答指出,代码的问题在于你迭代name in names但不在循环中使用name。它应该是i in seq_along(names)

然而,更大的问题是那些循环是无效且容易出错的。评论中的@akrun建议是使用paste0,但是以矢量化的方式,即。在循环之外。因此:

adress_part1 <- "https://www.google.com/trends/explore#q="
names <- c("lening", "krediet")
adress_part3 <- "&geo=NL&date=today%203-m&cmpt=q&tz=Etc%2FGMT-2"

total_adress <- paste0(adress_part1, names, adress_part3)

> total_adress
[1] "https://www.google.com/trends/explore#q=lening&geo=NL&date=today%203-m&cmpt=q&tz=Etc%2FGMT-2" 
[2] "https://www.google.com/trends/explore#q=krediet&geo=NL&date=today%203-m&cmpt=q&tz=Etc%2FGMT-2"