将data.Frame列名传递给使用Purrr::map的函数 [英] Pass a data.frame column name to a function that uses purrr::map
本文介绍了将data.Frame列名传递给使用Purrr::map的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在处理嵌套的数据帧,希望将顶级数据帧的名称和包含低级数据帧的列的名称传递给使用Purrr::map迭代低级数据框的函数。
这里有一个玩具示例。
library(dplyr)
library(purrr)
library(tibble)
library(tidyr)
df1 <- tibble(x = c("a","b","c", "a","b","c"), y = 1:6)
df1 <- df1 %>%
group_by(x) %>%
nest()
testfunc1 <- function(df) {
df <- df %>%
mutate(out = map(data, min))
tibble(min1 = df$out)
}
testfunc2 <- function(df, col_name) {
df <- df %>%
mutate(out = map(col_name, min))
tibble(min2 = df$out)
}
df1 <- bind_cols(df1, testfunc1(df1))
df1 <- bind_cols(df1, testfunc2(df1, "data"))
df1$min1
df1$min2
测试函数1的行为符合预期,在本例中,它给出了新列中每个数据列的最小值。在我试图传递列名的测试函数2中,一个名为"data"的字符串被传递给新列。我想我从这里的帖子(Pass a data.frame column name to a function)中理解了为什么这不是我想要的行为,但我还不能想出在这种情况下如何使它工作。任何建议都是很棒的。
推荐答案
这应该适用于您,它使用tidy eval框架。这假设ol_name是一个字符串。
testfunc2 <- function(df, col_name) {
df <- df %>%
mutate(out = map(!! rlang::sym(col_name), min))
tibble(min2 = df$out)
}
编辑:
如果您希望将裸列名称传递给函数,而不是字符串,请使用enquo
而不是sym
。
testfunc2 <- function(df, col_name) {
col_quo = enquo(col_name)
df <- df %>%
mutate(out = map(!! col_quo, min))
tibble(min2 = df$out)
}
这篇关于将data.Frame列名传递给使用Purrr::map的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文