【问题标题】:How do I change two for loops to apply如何更改两个 for 循环以应用
【发布时间】:2020-11-10 22:58:24
【问题描述】:

如何将两个for 循环更改为apply

df_trips <- data.frame(Origin=character(), 
Destination=character(), 
Trip=character(),
stringsAsFactors=FALSE) 

for(i in 1:4){
  for(j in 1:4){
      Origin=i
      Destination=j
      Trip=od_matrix[i,j]
      df_temp <- data.frame(Origin,Destination,Trip)
      df_trips= rbind(df_trips,df_temp)
  }
}

【问题讨论】:

  • 你能正确地格式化你的问题吗?您是否有特殊原因要移植所有应用?

标签: r for-loop apply lapply mapply


【解决方案1】:

您的整个代码可以缩短为一行:

cbind(expand.grid(Destination = 1:4, Origin = 1:4)[2:1], Trip = as.vector(t(od_matrix)))

你还没有给我们od_matrix,所以我们假设它看起来像这样:

od_matrix <- matrix(1:16, nrow = 4)
od_matrix
#>      [,1] [,2] [,3] [,4]
#> [1,]    1    5    9   13
#> [2,]    2    6   10   14
#> [3,]    3    7   11   15
#> [4,]    4    8   12   16

现在:

cbind(expand.grid(Destination = 1:4, Origin = 1:4)[2:1], Trip = as.vector(t(od_matrix)))
#>    Origin Destination Trip
#> 1       1           1    1
#> 2       1           2    5
#> 3       1           3    9
#> 4       1           4   13
#> 5       2           1    2
#> 6       2           2    6
#> 7       2           3   10
#> 8       2           4   14
#> 9       3           1    3
#> 10      3           2    7
#> 11      3           3   11
#> 12      3           4   15
#> 13      4           1    4
#> 14      4           2    8
#> 15      4           3   12
#> 16      4           4   16

结果是一样的

df_trips <- data.frame(Origin=character(), 
Destination=character(), 
Trip=character(),
stringsAsFactors=FALSE) 

for(i in 1:4){
  for(j in 1:4){
      Origin=i
      Destination=j
      Trip=od_matrix[i,j]
      df_temp <- data.frame(Origin,Destination,Trip)
      df_trips= rbind(df_trips,df_temp)
  }
}
df_trips
#>    Origin Destination Trip
#> 1       1           1    1
#> 2       1           2    5
#> 3       1           3    9
#> 4       1           4   13
#> 5       2           1    2
#> 6       2           2    6
#> 7       2           3   10
#> 8       2           4   14
#> 9       3           1    3
#> 10      3           2    7
#> 11      3           3   11
#> 12      3           4   15
#> 13      4           1    4
#> 14      4           2    8
#> 15      4           3   12
#> 16      4           4   16

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多