首先,我找不到符合此要求的答案。
我正在做这个功能
find.childrens <- function(categoria){
x <- fromJSON(paste("https://api.mercadolibre.com/categories/",categoria,sep=""))
if(!is.null(nrow(x$children_categories))){
for(i in 1:nrow(x$children_categories)){
find.childrens(x$children_categories[i,1])}
}else{print(x$id)}
}
saving <- find.childrens(categoria="MLA122518")
有效,但我不能保存返回(返回到打印的位置)
任何人都知道如何帮助我? 此致!
答案 0 :(得分:2)
如果你想要一个类别下的所有类别,递归函数应该总是返回一些东西并且可能连接id:
find.childrens <- function(categoria){
x <- fromJSON(paste("https://api.mercadolibre.com/categories/",categoria,sep=""))
ids <- NULL
if(!is.null(nrow(x$children_categories))){
for(i in 1:nrow(x$children_categories)){
ids <- c(ids, find.childrens(x$children_categories[i,1]))
}
}else{
ids <- x$id
}
return(ids)
}
saving <- find.childrens(categoria="MLA122518")
> saving
[1] "MLA385241" "MLA385242"
答案 1 :(得分:0)
您需要通过函数存储并返回每次递归跳转返回的值:
library("jsonlite")
find.childrens <- function(categoria) {
x <- fromJSON(paste("https://api.mercadolibre.com/categories/", categoria, sep=""))
count <- 0L
if (length(x[["children_categories"]])) {
for(i in seq_along(x[["children_categories"]][["id"]])) {
count <- count + find.childrens(x[["children_categories"]][i,"id"])
}
} else {
count <- x[["total_items_in_this_category"]]
}
count
}
(saving <- find.childrens(categoria="MLA122518"))
## [1] 113