使用R中的For循环将元素添加到列表中

问题描述 投票:0回答:1

我正在尝试创建一个简单的数据框,其中包含有关哪些作者及其各自论文的信息。我有一个矩阵,其中包含作者ID作为行,而纸张ID作为列。该矩阵包含1和0,其中1表示作者在该论文上工作。例如,如果A2P [1,1] == 1,则表示ID为1的作者正在处理ID为1的纸张。

我正在尝试将此矩阵转换为包含所有这些关系的简单数据框,其中仅包含作者ID和他们处理的论文。就像,

au_ID  P_ID
1      1
1      12        # Author 1 has worked on both paper 1 and 12
2      1         # Author 2 has also worked on paper 1, in addition to papers 2 and 3. 
2      2
2      3 
...

这是我在做什么:

list1 <- list()
list2 <- list()
# Rows are Author IDs
# Columns are Paper IDs
for (row in 1:nrow(A2P)){
  for (col in 1:ncol(A2P)){
    if (A2P[row,col] == 1){
      list1 <- append(list1, row)
      list2 <- append(list2, col)
    }
  }
}
authorship["au_ID"] = list1
authorship["P_ID"] = list2

我很难使此代码快速运行。它需要永远运行,现在要进行20分钟。我认为这与将每个行和列的值附加到每个列表有关,但是我不确定。

任何帮助将不胜感激!非常感谢!

我正在尝试创建一个简单的数据框,其中包含有关哪些作者及其各自论文的信息。我有一个矩阵,其中包含作者ID作为行,而纸张ID作为......>

r list for-loop append
1个回答
0
投票

您可能需要which(A2P == 1L, arr.ind = TRUE)

mat <- matrix(c(1L, 0L, 0L, 0L, 1L, 1L, 1L, 0L, 1L), ncol = 3)

mat
#     [,1] [,2] [,3]
#[1,]    1    0    1
#[2,]    0    1    0
#[3,]    0    1    1

which(mat == 1L, arr.ind = TRUE)
#     row col
#[1,]   1   1
#[2,]   2   2
#[3,]   3   2
#[4,]   1   3
#[5,]   3   3
© www.soinside.com 2019 - 2024. All rights reserved.