[英]R purrr map show column names in output
I'm trying to run purrr map
across vector inputs, and in the output i'd like the output columns to have meaningful names. 我试图跨向量输入运行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))
This is the output I expect, which has column names a
and b
: 这是我期望的输出,它具有列名a
和b
:
# A tibble: 1 x 2
# a b
# <chr> <chr>
# pre a end. pre b end.
Is there a way to avoid the need to run 有没有办法避免运行的需要
names(x) <- x
ie 即
x <- c("a", "b")
y <- "end."
map_dfc(x, function(x) paste("pre ", x, y))
# A tibble: 1 x 2
# a b
# <chr> <chr>
yields the data.frame/tibble with column names already attached? 产生具有已附加列名的data.frame / tibble吗?
I use map alot and often forget if the input vector has names or not. 我经常使用地图,并且经常忘记输入向量是否具有名称。
One easy method is to have input elements named. 一种简单的方法是命名输入元素。 This usually result in more consistent code. 这通常会导致代码更加一致。
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))
In addition to @RonakShah's comment suggesting setNames()
, you can handle this without purrr::map()
: 除了@RonakShah的建议setNames()
的注释之外,您也可以不使用purrr::map()
处理此问题:
paste("pre ", x, y) %>%
as.list() %>%
as.data.frame(col.names = x, stringsAsFactors = F)
The purrr
way is to use set_names
as in the comments, (although correct setNames
seems to be replaced by set_names
in purrr
): purrr
方式是在注释中使用set_names
(尽管正确的setNames
似乎被purrr
的set_names
purrr
):
map_dfc(set_names(x), function(x) paste("pre ", x, y))
With set_names
you don't need to specify the new names if you use the default argument. 使用set_names
,如果使用默认参数,则无需指定新名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.