【问题标题】:Is there a way that I could use a vector instead of this for loop?有没有办法可以使用向量而不是这个 for 循环?
【发布时间】:2020-08-11 17:58:26
【问题描述】:

我正在尝试遍历 R 中的一堆文件并访问每个文件中的信息。不用说,循环慢得令人难以忍受。有没有办法可以矢量化它?

library("rjson")

all_files=list.files(path="~/p/a/t/h", recursive = TRUE)

for(i in seq_along(all_files)) {
    temp = fromJSON(file = all_files[i])
    if (length(temp$tags) != 0){
        songTags <- c(songTags, temp$tags)
        songTrack_id <- c(songTrack_id, temp$track_id)
    }
}

【问题讨论】:

  • 如果其中一个答案解决了您的问题,请accept it;这样做不仅为回答者提供了一些积分,而且还为有类似问题的读者提供了一些关闭。尽管您只能接受一个答案,但您可以选择对您认为有帮助的人进行投票。 (如果仍有问题,您可能需要编辑您的问题并提供更多详细信息。)

标签: r for-loop vectorization


【解决方案1】:

未经测试:

rawdat <- lapply(all_files, fromJSON)
hastags <- sapply(rawdat, function(x) "tags" %in% names(rawdat))
if (any(hastags)) {
  songTags <- unlist(lapply(rawdat[hastags], `[[`, "tags"))
  songTracks <- unlist(lapply(rawdat[hastags], `[[`, "track_id"))
}

【讨论】:

    【解决方案2】:

    在循环中增长对象通常非常昂贵/缓慢。您可以使用lapply/sapply

    all_data <- do.call(rbind, lapply(all_files, function(x) {
                    temp = jsonlite::fromJSON(file = x)
                    if(length(temp$tags)) 
                       list(tags = temp$tags, track_id = temp$track_id)
                }))
    

    或者使用purrrmap_df的更短的选项

    all_data <- map_df(all_files, ~{
                   temp = jsonlite::fromJSON(file = .x)
                   if(length(temp$tags)) 
                      list(tags = temp$tags, track_id = temp$track_id)
                   })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多