有没有一种方法可以使用向量代替for循环?

时间:2020-04-28 02:02:50

标签: r for-loop vectorization

我正在尝试遍历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)
    }
}

2 个答案:

答案 0 :(得分:0)

在循环中生长对象通常非常昂贵/缓慢。您可以使用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)
            }))

或更短的选项使用purrr的{​​{1}}

map_df

答案 1 :(得分:0)

未经测试:

<div class="sidenav_container"  [@onSideNavChange]="sideNavState ? 'open' : 'close'">
  <div fxLayout="column" fxLayoutGap="10px" style="height: 100%;">

    <div class="user_menu text-center">
      <mat-nav-list >
        <a mat-list-item >
          <img class="jim" src="https://a57.foxnews.com/media2.foxnews.com/BrightCove/694940094001/2018/06/21/931/524/694940094001_5800293009001_5800284148001-vs.jpg?ve=1&tl=1" alt="">
          <span [@animateText]="linkText ? 'show' : 'hide'">{{ page?.name }} </span>
        </a>
      </mat-nav-list>
      <mat-divider></mat-divider>
    </div>

    <div>
      <header style="text-align:center; background-color:lightgray; color:royalblue;">Links</header>
      <mat-nav-list>
        <a mat-list-item *ngFor="let page of pages">
          <mat-icon style="padding-right:5px;">{{page?.icon}}</mat-icon>
          <span [@animateText]="linkText ? 'show' : 'hide'">{{ page?.name }} </span>
        </a>
      </mat-nav-list>
    </div>
  </div>

  <span class="spacer"></span>
  <div fxLayout="row" fxLayoutAlign="end end" style="padding: 0px 10px;">
    <button mat-icon-button (click)="onSinenavToggle()">
      <mat-icon *ngIf="sideNavState">arrow_left</mat-icon>
      <mat-icon *ngIf="!sideNavState">arrow_right</mat-icon>
    </button>
  </div>
</div>