【问题标题】:Custom API function to add country codes to data frame in R自定义API函数将国家代码添加到R中的数据框
【发布时间】:2021-02-17 01:02:23
【问题描述】:

我正在尝试将我制作的函数应用于我的数据框的每一行,以获取与该国家/地区关联的国家/地区代码。当我在国家/地区单独测试我的功能时,它可以工作。

library(jsonlite)
library(httr)

get_country_codes <- function(countryname){
    
url<-'https://restcountries.eu/rest/v2/name/'

url<- paste(url,countryname,sep="")

raw_result=GET(url)
    
    

get_codes_text <- content(raw_result, "text")



get_codes <- fromJSON(get_codes_text)
    


return(get_codes[4])


}

当我将该功能应用到这样的任何国家/地区时,这有效

get_country_codes('Andorra')

但是当我尝试将它应用到我的数据框“国家”列时

new_df <- apply(country_data['Country'], 1, function(x) get_country_codes(x))
new_df

它主要是给我 NA。

我不确定我的 apply 功能发生了什么,我已经在各个国家/地区进行了测试,它几乎适用于所有国家。

【问题讨论】:

  • “国家”是一个因素而不是一个字符向量吗?如果这没有帮助,您需要在问题中包含一些示例数据,以便人们可以重现它。

标签: r dataframe apply


【解决方案1】:

使用sapply

new_df <- sapply(country_data$Country, get_country_codes)

【讨论】:

    【解决方案2】:

    我们可以使用map

    library(purrr)
    new_df <- map(country_data$Country, get_country_codes)
    

    【讨论】:

      猜你喜欢
      • 2021-02-02
      • 1970-01-01
      • 2016-12-29
      • 1970-01-01
      • 1970-01-01
      • 2018-10-16
      • 1970-01-01
      • 2021-03-16
      • 2015-06-27
      相关资源
      最近更新 更多