英文:
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("df_name")
as a placeholder. How can I replace this to get the name of the actual dataframe?
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=paste0("df_name"))
}
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 <- function(df,nm){
df |>
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()
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论