首页 > 解决方案 > R中的矢量化操作导致自定义函数出现问题

问题描述

我正在写一些用于库存管理的功能。我最近想通过使用我在最初构建库存时成功使用的 API 在我的电子表格中添加一个“照片 url 列”。我的电子表格标题如下所示:

SKU | NAME | OTHER STUFF

我有一个getProductInfo函数可以从我正在调用的 API 返回产品信息列表。

getProductInfo<- function(barcode) {
    #Input UPC
    #Output List of product info
    CallAPI(barcode)
    Process API return, remove garbage
    return(info)
}

我创建了一个新函数,将我的库存 csv 作为输入,并尝试添加一个带有产品照片 url 的新列。

get_photo_url_from_product_info_output <- function(in_list){
  #Input GetProductInfo Output. Returns Photo URL, or nothing if
  #it doesn't exist
  if(in_list$DisplayStockPhotos == TRUE){
    return(in_list$StockPhotoURL)
  } else {
    return("")
  }
}

add_Photo_URL <- function(in_csv){
  #Input CSV data frame, appends photourl column
  #Requires SKU (UPC) assumes no photourl column

  out_csv <- mutate(in_csv, photo =
                  get_photo_url_from_product_info_output(
                    getProductInfo(SKU)
                    )
                )
}
  
  return (out_csv)
}

#Call it
new <- add_Photo_URL(old)

我的想法是,R 会简单地从行中输入 SKU,然后“按原样”通过双函数调用,向量化的 DPLYR 函数mutate只会对其进行向量化。不幸的是,我遇到了各种我无法理解的问题。最终我发现 API 调用崩溃了,因为该SKU字段在传入时全部搞砸了。我设置了一个断点,发现它不仅仅是传入 SKU,而是整个列表(我认为?) 的 SKU。每一行一次。像这样的东西:

#Variable 'barcode' inside getProductInfo function contains:
 [1] 7.869368e+11 1.438175e+10 1.256983e+10 2.454357e+10 3.139814e+10 1.256983e+10 1.313260e+10 4.339643e+10 2.454328e+10
 [10] 1.313243e+10 6.839046e+11 2.454367e+10 2.454363e+10 2.454367e+10 2.454348e+10 8.418870e+11 2.519211e+10 2.454375e+10
 [19] 2.454381e+10 2.454381e+10 2.454383e+10 2.454384e+10 7.869368e+11 2.454370e+10 2.454390e+10 1.913290e+11 2.454397e+10
 [28] 2.454399e+10 2.519202e+10 2.519205e+10 7.742121e+11 8.839291e+11 8.539116e+10 2.519211e+10 2.519211e+10 2.519211e+10

显然我的初始getProductInfo函数无法处理,所以它会崩溃。我应该如何修改我的代码,无论是在输入还是 API 调用中,以避免这种矢量化操作问题?

标签: r

解决方案


Well, it's not totally elegant but it works.

I figured out I need to use lapply, which is usually not my strong suit. Initally I tried to nest them like so:

lapply(SKU, get_photo_url_from_product_info_output(getProductInfo())

But that didn't work. So I just came up with bright idea of making another function

get_photo_url_from_sku <- function(barcode){
  return(get_photo_url_from_product_info_output(getProductInfo(barcode)))
}

Call that in the lapply:

out_csv<- mutate(in_csv, photocolumn = lapply(SKU, get_photo_url_from_sku))

And it works great. My speed is only limited by my API calls.


推荐阅读