gpt4 book ai didi

r - 将 data.frame 列名称传递给使用 purrr::map 的函数

转载 作者:行者123 更新时间:2023-12-02 20:23:22 24 4
gpt4 key购买 nike

我正在使用嵌套数据帧,并希望将顶级数据帧的名称以及包含较低级别数据帧的列的名称传递给使用 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

testfunc1 的行为符合预期,在本例中给出了新列中每个数据列的最小值。在 testfunc2 中,我尝试传递列名称,一个读取“data”的字符串被传递到新列。我想我从这里的线程( Pass a data.frame column name to a function )中理解了为什么这没有达到我想要的效果,但我无法弄清楚如何让它在这种情况下工作。任何建议都会很棒。

最佳答案

这应该适合你,它使用 tidy eval框架。这假设 col_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)

}

关于r - 将 data.frame 列名称传递给使用 purrr::map 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50685220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com