R purrr map show column names in output

拜拜、爱过 提交于 2020-01-15 10:13:25

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!