R new variable assignment

前端 未结 1 1621
孤街浪徒
孤街浪徒 2021-01-27 12:37

I made a loop that assigns the result of a function to a newly created variable. After that that variable is used to create another. This second step fails to produce the expect

1条回答
  •  旧巷少年郎
    2021-01-27 12:59

    Don't create a bunch of variables, store related values in named lists to make it easier to retrieve them. You didn't supply any input to test with, but i'm guessing this does the same thing.

    library(stringr)
    mydata <- lapply(1:length(Ids), function(i) {
        dd <- GetReportData(query, token,paginate_query = F))
        dd$contentid <- str_extract(d$pagePath,"&id=[0-9]+"))
        dd
    })
    

    This will return a list of data.frames. You can access them with mydata[[1]], mydata[[2]], etc rather than data_1, data_2, etc

    If you absolutely insist on creating a bunch of variables, just make sure to do all your transformations on an actual object, and then save that object when your are done. You can never use assign with names that have $ or [ as described in the help page: "assign does not dispatch assignment methods, so it cannot be used to set elements of vectors, names, attributes, etc." For example

    for(i in 1:length(Ids)) {
        dd <- GetReportData(query, token,paginate_query = F))
        dd$contentid <- str_extract(d$pagePath,"&id=[0-9]+"))
        assign(paste("data",i,sep="_"), dd)
    }
    

    0 讨论(0)
提交回复
热议问题