R dplyr - get variable name as string in mutate/summarise

心不动则不痛 提交于 2019-12-11 04:55:11

问题


I have been trying unsuccessfully to extract the name of a variable that was passed to a function in dplyr::mutate(). Below is a short example where I want to create a function that returns the string "mpg" inside mutate:

# mtcars dataset with grouping variable
dataset = mtcars
dataset$group = c(1, 2, 3, 4)

# function to call inside mutate()
f = function(col, data){
  str_col = deparse(lazyeval::expr_find(col))
  str_col
}

# this does not work: returns the content of mpg 
# instead of the variable name as a string
dataset %>%
  group_by(group) %>%
  mutate(f = f(mpg, dataset)
  ) %>%
  select(group, f)

I used lazyeval::expr_find(), because subsitute only "goes up" one layer as far as I understood the documentation. It works when I call f() inside the function wrap(), but it returns the content of mpg, instead of the name "mpg" when I put it inside group_by()%>%mutate()

I found some questions that are related, but none of them provided a solution to my problem.

Any help greatly appreciated:)


回答1:


I'm still not entirely clear on what you are trying to do, but maybe this helps:

f = function(col, data){
  str_col = deparse(substitute(col))
  data.frame(str_col)
}

dataset %>% 
   group_by(group) %>% 
   do(f(mpg, .))


来源:https://stackoverflow.com/questions/42679510/r-dplyr-get-variable-name-as-string-in-mutate-summarise

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