【问题标题】:Any way to add rownames to a tibble in R将行名添加到 R 中的小标题的任何方法
【发布时间】:2020-11-01 08:41:39
【问题描述】:

我正在尝试更改 tibble 中的 rownames,该 tibble 由下面的 purrr 包中的 map_dfr 循环函数输出,但未成功。有解决办法吗?

foo <- function(x){
     total <- rbinom(1, x, .5)
     fixed <- total - 2
    random <- fixed + 3
   c(total = total, fixed = fixed, random = random)
}

m <- purrr::map_dfr(.x = c(6:9), .f = foo) # loop and output a tibble (a data.frame)
rownames(m) <- paste0("m", 1:4) # change the rownames
m

但是rownames不要改变:

# A tibble: 4 x 3
  total fixed random
* <dbl> <dbl>  <dbl>
1     2     0      3
2     3     1      4
3     4     2      5
4     2     0      3

【问题讨论】:

    标签: r loops dataframe tidyverse


    【解决方案1】:

    它是tibble,并且 tibble 不能有自定义的行名。一种选择是转换为data.frame,然后分配行名

    m <- as.data.frame(m)
    rownames(m) <- paste0("m", 1:4)
    m
    #   total fixed random
    #m1     3     1      4
    #m2     5     3      6
    #m3     2     0      3
    #m4     5     3      6
    

    如果我们想保留一列用于标识,map 也有 .id,其中将包括 list 名称(如果存在)或 list 的序列

    purrr::map_dfr(.x = 6:9, .f = foo, .id = 'm')
    purrr::map_dfr(.x = setNames(6:9, paste0("m", 1:4)), .f = foo, .id = 'm')
    

    【讨论】:

    • @rnorouzian 根据文档here,允许有列而不是行名
    • @rnorouzian 这是 tibble 和 data.table 的技术限制
    • @rnorouzian 如果存在现有的 row.names,它将剥离它,即 mtcars %&gt;% as_tibble
    • @rnorouzian 我的意思是 6:9 作为长度 4。如果你已经有一个列表。然后map_dfr(setNames(lst1, paste0("m", seq_along(lst1))), .f = foo, .id = 'm')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 2022-12-18
    • 2021-09-21
    • 2012-12-10
    相关资源
    最近更新 更多