rno*_*ian 3 loops r dataframe tidyverse
我试图更改下面包中循环函数输出的rownames ,但没有成功。有解决办法吗?tibblemap_dfrpurrr
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
Run Code Online (Sandbox Code Playgroud)
但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
Run Code Online (Sandbox Code Playgroud)
它是一个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
Run Code Online (Sandbox Code Playgroud)
如果我们想保留一列用于识别,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')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9679 次 |
| 最近记录: |