【问题标题】:Adding Elements to List using For Loop in R在 R 中使用 For 循环将元素添加到列表
【发布时间】:2020-08-12 23:18:27
【问题描述】:

我正在尝试创建一个简单的数据框,其中包含有关作者及其各自论文的信息。我有一个矩阵,其中包含作为行的作者 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

我很难让这段代码快速运行。它需要永远运行,现在持续二十分钟。我认为这与将每一行和每一列的值附加到每个列表有关,但我不确定。

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

【问题讨论】:

    标签: r list for-loop append


    【解决方案1】:

    你可能需要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
    

    在这种情况下,row 将对应于au_IDcol 将对应于P_ID。然后以您的格式完全获取它:

    authorship <- which(mat == 1L, arr.ind = TRUE)
    colnames(authorship) <- c('au_ID', 'P_ID')
    
    as.data.frame(authorship)
    ##  au_ID P_ID
    ##1     1    1
    ##2     2    2
    ##3     3    2
    ##4     1    3
    ##5     3    3
    

    【讨论】:

    • 不错的解决方案,喜欢简单
    • 非常感谢!我的代码确实完成了运行,并且我能够使用以下命令创建我想要的数据框:authorship &lt;- do.call(rbind, Map(data.frame, au_ID=list1, P_ID=list2))
    • 然而,你的更紧凑,不使用循环。非常感谢!我真的很感激,因为我对 R 很陌生 - 我试图将 python 语法与整个 authorship["au_ID"] 一起使用。
    猜你喜欢
    • 2015-01-25
    • 1970-01-01
    • 2017-09-22
    • 2016-08-25
    • 2019-04-08
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多