简体   繁体   中英

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.

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

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?

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() :

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 ):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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