我试图使用R从URL获得响应。我可以使用httr::GET
和httr::content
成功地编写代码:
library(tidyverse)
library(httr)
test <- GET ("https://www.ebi.ac.uk/cgi-bin/ipd/imgt/hla/dpb_v2.cgi?pid=1&patdpb1=01:01&patdpb2=04:01&did=2&dondpb1=01:01&dondpb2=01:01")
%>% content(as = "text")
我想对数据帧的每一行都这样做。数据类似如下:
test <- tribble(~case, ~mDPB11cd.recipient, ~mDPB12cd.recipient, ~mDPB11cd.donor, ~mDPB12cd.donor,
101, "04:01", "01:01", "03:01", "04:01",
102, "04:01", "02:01", "04:01", "01:01",
103, "01:01", "104:01", "03:01", "05:01",)
我已经编写了代码,为每一行组装正确的url,并且可以使用purrr::map
获得每个响应:
DPB1_permisive <- test
%>% mutate (url = (paste0("https://www.ebi.ac.uk/cgi-bin/ipd/imgt/hla/dpb_v2.cgi?pid=1&patdpb1=", mDPB11cd.recipient, "&patdpb2=", mDPB12cd.recipient, "&did=2&dondpb1=", mDPB11cd.donor, "&dondpb2=", mDPB12cd.donor)))
%>% mutate (result = (map(url, GET)))
然而,现在我找不到任何方法来使用content
来解析我得到的结果。
%>% content(result, as = "text")
在上面的代码中使用会产生一个错误
内容错误(。, result, as = "text"): is.response(x)不是TRUE
似乎URL的结果没有正确地写入数据帧中。"result"列显示为类型"列表",";每行的值为S3: response>.">
如何让content
解析响应?
您可以使用map
从GET
请求中获取数据。
library(tidyverse)
library(httr)
test %>%
mutate(url = paste0("https://www.ebi.ac.uk/cgi-bin/ipd/imgt/hla/dpb_v2.cgi?pid=1&patdpb1=", mDPB11cd.recipient, "&patdpb2=", mDPB12cd.recipient, "&did=2&dondpb1=", mDPB11cd.donor, "&dondpb2=", mDPB12cd.donor),
result = map(url, GET),
data = map(result, content, as = "text"))
# case mDPB11cd.recipie… mDPB12cd.recipie… mDPB11cd.donor mDPB12cd.donor url result data
# <dbl> <chr> <chr> <chr> <chr> <chr> <list> <lis>
#1 101 04:01 01:01 03:01 04:01 https://www.ebi.ac.uk/c… <resp… <chr…
#2 102 04:01 02:01 04:01 01:01 https://www.ebi.ac.uk/c… <resp… <chr…
#3 103 01:01 104:01 03:01 05:01 https://www.ebi.ac.uk/c… <resp… <chr…