繁体   English   中英

R purrr映射在输出中显示列名称

[英]R purrr map show column names in output

我试图跨向量输入运行purrr map ,在输出中我希望输出列具有有意义的名称。

x <- c("a", "b")
y <- "end."

map_dfc(x, function(x) paste("pre ", x, y))

names(x) <- x
map_dfc(x, function(x) paste(x, y))

这是我期望的输出,它具有列名ab

# A tibble: 1 x 2
# a      b     
# <chr>  <chr> 
# pre  a end. pre  b end.

有没有办法避免运行的需要

names(x) <- x

x <- c("a", "b")
y <- "end."

map_dfc(x, function(x) paste("pre ", x, y))
# A tibble: 1 x 2
# a      b     
# <chr>  <chr> 

产生具有已附加列名的data.frame / tibble吗?

我经常使用地图,并且经常忘记输入向量是否具有名称。

一种简单的方法是命名输入元素。 这通常会导致代码更加一致。

library(purrr)
x <- setNames(c("a", "b"), nm = c("a", "b"))
# x <- setNames(nm = c("a", "b")) # this is short cut of above
y <- "end."
map_dfc(x, function(x) paste("pre ", x, y))

除了@RonakShah的建议setNames()的注释之外,您也可以不使用purrr::map()处理此问题:

paste("pre ", x, y) %>% 
  as.list() %>%
  as.data.frame(col.names = x, stringsAsFactors = F)

purrr方式是在注释中使用set_names (尽管正确的setNames似乎被purrrset_names purrr ):

map_dfc(set_names(x), function(x) paste("pre ", x, y))

使用set_names ,如果使用默认参数,则无需指定新名称。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM