R purrr 映射在输出中显示列名 [英] R purrr map show column names in output
问题描述
我正在尝试跨向量输入运行 purrr map
,在输出中我希望输出列具有有意义的名称.
I'm trying to run purrr map
across vector inputs, and in the output i'd like the output columns to have meaningful names.
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))
这是我期望的输出,它有列名 a
和 b
:
This is the output I expect, which has column names a
and 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
即
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?
yields the data.frame/tibble with column names already attached?
我经常使用地图,但经常忘记输入向量是否有名称.
I use map alot and often forget if the input vector has names or not.
推荐答案
purrr
的方式是使用 set_names
作为注释,(尽管正确的 setNames
似乎被 purrr
中的 set_names
替换了):
The purrr
way is to use set_names
as in the comments, (although correct setNames
seems to be replaced by set_names
in purrr
):
map_dfc(set_names(x), function(x) paste("pre ", x, y))
使用 set_names
如果使用默认参数,则无需指定新名称.
With set_names
you don't need to specify the new names if you use the default argument.
这篇关于R purrr 映射在输出中显示列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!