Home > Back-end >  Passing multiple dataframes to a function that contains an if statement in R
Passing multiple dataframes to a function that contains an if statement in R

Time:05-27

I have a function below that contains an IF statement, the error message is:

1: In if (df == "iris1") { : the condition has length > 1 and only the first element will be used

Can anyone amend the code so that it works?

library(tidyverse)
iris1<-iris[1:50, ]
iris2<-iris[51:100,]

add_col<-function(df,colname)
  {
    df$newcol<-df [, colname]*100
if(df=="iris1"){df<-df%>%mutate(col_id="some text")}    
if(df=="iris2"){df<-df%>%mutate(col_id="other text")}    
return(df) 
}

x <- c("iris1", "iris2")

z<-map(map(x, ~ as.symbol(.x) %>% eval),
    ~ add_col(.x, "Sepal.Length"))

CodePudding user response:

Create a named list and then use imap to loop over the list

library(purrr)
add_col<-function(df, nm, colname)
  {
    df$newcol<-df [, colname]*100
if(nm =="iris1"){df<-df%>% mutate(col_id="some text")}    
if(nm=="iris2"){df<-df%>%mutate(col_id="other text")}    
return(df) 
}

-testing

out <- imap(lst(iris1, iris2), ~ add_col(.x, .y, "Sepal.Length"))
> map(out, head, 2)
$iris1
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species newcol    col_id
1          5.1         3.5          1.4         0.2  setosa    510 some text
2          4.9         3.0          1.4         0.2  setosa    490 some text

$iris2
   Sepal.Length Sepal.Width Petal.Length Petal.Width    Species newcol     col_id
51          7.0         3.2          4.7         1.4 versicolor    700 other text
52          6.4         3.2          4.5         1.5 versicolor    640 other text
  •  Tags:  
  • r
  • Related