获取在运行函数时的命名数据框的名称。

huangapple go评论50阅读模式
英文:

Get the name of the named dataframe when running a function

问题

我有一个命名的数据框列表,并在它们上运行一个函数,如下所示。

我需要在运行函数时获取数据框的名称。

在下面的示例中,我想要添加一个包含数据框名称的列,并输入了paste0("df_name")作为占位符。如何替换这个以获取实际数据框的名称?

library(tidyverse)

df_list <- list()

df_list$iris1 <- iris[1:50,]
df_list$iris2 <- iris[51:100,]
df_list$iris3 <- iris[101:150,]

df_name <- function(df){
    df %>%
    mutate(df_name = deparse(substitute(df)))
}

map(df_list, df_name)
英文:

I have a list of named dataframes and run a function on them as below.

I need to get the name of the dataframe whilst running the function.

In the example below I want to add a column with the name of the dataframe in and have entered paste0(&quot;df_name&quot;) as a placeholder. How can I replace this to get the name of the actual dataframe?

library(tidyverse)

df_list&lt;-list()

df_list$iris1&lt;-iris[1:50,]
df_list$iris2&lt;-iris[51:100,]
df_list$iris3&lt;-iris[101:150,]

df_name&lt;-function(df){
    df%&gt;%
    mutate(df_name=paste0(&quot;df_name&quot;))
}

map(df_list,df_name)

</details>


# 答案1
**得分**: 2

只使用 `purrr::imap()` 处理表达式上的复杂计算,不要与之纠缠不清:

```R
df_name <- function(df, nm){
  df %>%
    mutate(nm = nm)
}

imap(df_list, .f = ~df_name(.x, .y))

imap() 在列表的名称和元素之间进行映射,因此您可以在应用函数时访问列表元素及其名称。这只是一个围绕map2() 的方便函数。

英文:

I wouldn't mess with complicated computations on expressions, just use purrr::imap():

df_name &lt;- function(df,nm){
  df |&gt;
    mutate(nm = nm)
}

imap(df_list,.f = ~df_name(.x,.y))

imap() maps over the names & elements of a list in tandem, so you have access to both the list element and it's name in the function you're applying. It's just a convenience function around map2().

huangapple
  • 本文由 发表于 2023年6月8日 00:33:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76425414.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定