问题
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))
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
i.e.
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?
I use map alot and often forget if the input vector has names or not.
回答1:
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))
回答2:
In addition to @RonakShah's comment suggesting setNames(), you can handle this without purrr::map():
paste("pre ", x, y) %>%
as.list() %>%
as.data.frame(col.names = x, stringsAsFactors = F)
回答3:
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))
With set_names you don't need to specify the new names if you use the default argument.
来源:https://stackoverflow.com/questions/53809045/r-purrr-map-show-column-names-in-output