简体   繁体   English

R-遍历变量名

[英]R - Iterate through variable names

I'm trying to iterate ( for ) through variables. 我试图通过变量迭代( )。 This is the code: 这是代码:

json_YR_FKA <- getURL('https://www.kimonolabs.com/api/b7i1ej7i?apikey=-')
json_9A_BTE <- getURL('https://www.kimonolabs.com/api/a83t52cg?apikey=-')

I will have two variables: json_YR_FKA / json_9A_BTE 我将有两个变量:json_YR_FKA / json_9A_BTE

matriculas <- ls()
matriculas <- str(matriculas)
matriculas

matriculas [1] "json_9A_BTE" "json_YR_FKA" 矩阵[1]“ json_9A_BTE”“ json_YR_FKA”

And now, I need to do some things with both variables, so I have a for iteration: 现在,我需要对两个变量都做一些事情,所以我有一个for迭代:

for (i in 1:total){
   avion <- fromJSON(matriculas[i])  
   # boring code
}

My idea is to do this: 我的想法是这样做:

First iteration: fromJSON(json_9A_BTE) Second iteration: fromJSON(json_YR_FKA) 第一次迭代:fromJSON(json_9A_BTE)第二次迭代:fromJSON(json_YR_FKA)

But at the beginning of the first iteration I get this: 但是在第一次迭代的开始我得到了这个:

fromJSON(matriculas[i]) Error in fromJSON(matriculas[1]) : unexpected character 'j' fromJSON(matriculas [i])中的fromJSON(matriculas [1])错误:意外字符'j'

And I don't know why. 而且我不知道为什么。

Anyone? 任何人?

Thanks in advance. 提前致谢。

Luis 路易斯

The approach that you're taking isn't very R-like, so I'm guessing you're coming from Python or some other language? 您采用的方法与R不太像,所以我猜您是来自Python还是其他语言?

First off, I'm not sure what packages you're using. 首先,我不确定您使用的是什么软件包。 Where does getURL() come from? getURL()来自哪里? Which JSON package are you using? 您正在使用哪个JSON包? I suggest jsonlite since it can just pull data in from the url. 我建议使用jsonlite,因为它可以从url中提取数据。

library(jsonlite)

myUrls <- c(json_YR_FKA='https://www.kimonolabs.com/api/b7i1ej7i?apikey=-',
            json_9A_BTE='https://www.kimonolabs.com/api/a83t52cg?apikey=-')

matriculas <- lapply(myUrls, fromJSON) #Provides a list of your data.

f_doSomething <- function(dat) {
    #boring code that puts data into 'out' variable
    return(out)
    }

avion <- lapply(matriculas, f_doSomething)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM