![](/img/trans.png)
[英]Passing multiple dataframes to a function that contains an if statement in R
[英]Passing a function to multiple dataframes at the same time
我有 3 個數據框:
iris1<-iris[1:50, ]
iris2<-iris[51:100,]
iris3<-iris[101:150,]
一個簡單的 function 接受 dataframe 和一列的輸入,並將該列乘以 100,然后返回 dataframe:
add_col<-function(df,colname)
{
df$newcol<-df [, colname]*100
return(df)
}
然后我可以在 dataframe 上使用 function 來添加額外的列:
iris1<-add_col(df=iris1,colname="Sepal.Length")
我怎樣才能將所有數據幀傳遞給這個 function 而不是重復上面的 3x(每個 dataframe 1 個?)。 我認為這是一個將 apply 系列用於函數的問題,但我無法弄清楚如何去做。
你可以做:
new_list <- lapply(list(iris1, iris2, iris3), add_col, colname = "Sepal.Length")
在這里,您將擁有三個數據框作為列表元素,您可以通過以下方式將它們作為真實數據框取回:
iris1_new <- new_list[[1]]
或者您可以執行以下操作將新列表元素分配給全局環境:
new_names <- c("iris1_new", "iris2_new", "iris3_new")
lapply(1:length(new_names), function(x) assign(x = new_names[x], value = new_list[[x]], envir = .GlobalEnv))
另一種可能的解決方案,基於purrr::map
:
library(tidyverse)
x <- c("iris1", "iris2", "iris3")
map(map(x, ~ as.symbol(.x) %>% eval),
~ add_col(.x, "Sepal.Length")) %>%
set_names(x) %>%
list2env(.GlobalEnv)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.