【问题标题】:Loop through list or a matrix in R循环遍历列表或 R 中的矩阵
【发布时间】:2020-07-24 20:51:10
【问题描述】:

Mfrq 是一个 608 x 10 的矩阵,list.ids 是一个包含 608 个用户的列表,每个用户包含 10 个项目。 我试图找到矩阵中每两行或列表中每两个向量之间的距离。 我期望输出为 608 x 608 的矩阵,其中包含距离。 附加的代码是我一直在运行和收到的错误。

<This is for the list>
rnext=row+1
for (row in 1:length(list.ids)){
  Wdist=as.matrix(wasserstein1d(list.ids[[row]],list.ids[[rnext]]))
  row=rnext
}

这个可行,但它只给我一个值。

<the value>
 Wdist
         [,1]
[1,] 2.585177

对于我拥有的矩阵:

i=1:nrow(Mfrq)
sapply(Mfrq, function(x) as.matrix({wasserstein1d(x[i,],x[i+1,])}) )

有错误

Error in x[i, ] : incorrect number of dimensions

我的矩阵看起来像

head(Mfrq)
             [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]      [,8]       [,9]
1029891  3.703704  6.172840  8.641975 24.691358 39.506173  4.938272  4.938272  3.703704  1.2345679
1044051  4.347826  8.695652  8.695652 21.739130 26.086957  4.347826 13.043478  0.000000  8.6956522
1056991  1.538462  0.000000 10.769231  4.615385  7.692308  9.230769  9.230769 33.846154 13.8461538
1069151  0.000000  0.000000  3.703704  3.703704  7.407407 14.814815 11.111111  7.407407 11.1111111
1071801  4.761905 19.047619 14.285714 23.809524  4.761905  9.523810  4.761905  9.523810  4.7619048
1072191 31.417625 29.118774 13.026820  9.578544  9.195402  3.831418  1.149425  1.149425  0.7662835
             [,10]
1029891  2.4691358
1044051  4.3478261
1056991  9.2307692
1069151 40.7407407
1071801  4.7619048
1072191  0.7662835

列表看起来像

$`1029891`
 [1]  3.703704  6.172840  8.641975 24.691358 39.506173  4.938272  4.938272  3.703704  1.234568  2.469136

$`1044051`
 [1]  4.347826  8.695652  8.695652 21.739130 26.086957  4.347826 13.043478  0.000000  8.695652  4.347826

$`1056991`
 [1]  1.538462  0.000000 10.769231  4.615385  7.692308  9.230769  9.230769 33.846154 13.846154  9.230769

$`1069151`
 [1]  0.000000  0.000000  3.703704  3.703704  7.407407 14.814815 11.111111  7.407407 11.111111 40.740741

$`1071801`
 [1]  4.761905 19.047619 14.285714 23.809524  4.761905  9.523810  4.761905  9.523810  4.761905  4.761905

$`1072191`
 [1] 31.4176245 29.1187739 13.0268199  9.5785441  9.1954023  3.8314176  1.1494253  1.1494253  0.7662835
[10]  0.7662835

【问题讨论】:

  • 头部已附上

标签: r loops matrix


【解决方案1】:

这里有一些问题。首先,如果您使用的是 for 循环,则不应更改迭代变量。你有:

for (row in 1:length(list.ids)){
  Wdist=as.matrix(wasserstein1d(list.ids[[row]],list.ids[[rnext]]))
  row=rnext
}

你不应该在这个循环中有row = rnext

问题:你需要计算每两个连续行之间的距离吗?或者,您是否需要为两行的每个组合计算它们?这两个是不同的。

如果要计算每两个连续行之间的距离,则row 变量必须从 1 到 9,rnext 变量必须从 2 到 10。

你的第二个问题是你没有在这个循环中保存任何东西:

for (row in 1:length(list.ids)){
  Wdist=as.matrix(wasserstein1d(list.ids[[row]],list.ids[[rnext]]))
  row=rnext
}

您在每次迭代中都会覆盖Wdist

你对矩阵部分也有类似的问题。

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 2021-04-13
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多