【问题标题】:Take row names from list of lists in R从 R 中的列表中获取行名
【发布时间】:2021-12-02 15:39:51
【问题描述】:

结果之类的列表开始:

id <- c(1,2,3,4,5,1,2,3,4,5)
month <- c(3,4,2,1,5,7,3,1,8,9)
preds <- c(0.5,0.1,0.15,0.23,0.75,0.6,0.49,0.81,0.37,0.14)

l_1 <- data.frame(id, preds, month)

preds <- c(0.45,0.18,0.35,0.63,0.25,0.63,0.29,0.11,0.17,0.24)

l_2 <- data.frame(id, preds, month)

preds <- c(0.58,0.13,0.55,0.13,0.76,0.3,0.29,0.81,0.27,0.04)

l_3 <- data.frame(id, preds, month)

preds <- c(0.3,0.61,0.18,0.29,0.85,0.76,0.56,0.91,0.48,0.91)

l_4 <- data.frame(id, preds, month)

outcome <- list(l_1, l_2, l_3, l_4)

我的兴趣是获取分配的唯一行值并像我们一样创建一个新变量:

sample <- outcome[[1]]
sample$unique_id <- rownames(sample)

但是,我不想手动进行,因为我的列表有 100 个列表。 此外,我不想为每一行手动分配值,因为我想保留 R 生成的行名。

有什么线索吗?

【问题讨论】:

    标签: r list variables purrr rowname


    【解决方案1】:

    尝试使用lapply

    lapply(outcome, function(x) {
      x$unique_id <- rownames(x)
      x
      })
    

    【讨论】:

      【解决方案2】:

      使用lapplycbind

      lapply(outcome, function(x) {
        cbind(unique_id=rownames(x), x)
        })
      

      【讨论】:

        【解决方案3】:

        我们也可以使用rownames_to_column

        library(dplyr)
        library(purrr)
        library(tibble)
        map(outcome, ~ .x %>%
            rownames_to_column('unique_id'))
        

        【讨论】:

          【解决方案4】:

          另一个基本 R 选项是使用 Map

          Map(function(x){
            x$unique_id <- rownames(x)
            x
          }, outcome)
          

          【讨论】:

            猜你喜欢
            • 2022-01-26
            • 1970-01-01
            • 2021-02-21
            • 2011-12-03
            • 2021-04-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-04-03
            相关资源
            最近更新 更多