简体   繁体   English

将多个数据帧传递给包含 R 中的 if 语句的函数

[英]Passing multiple dataframes to a function that contains an if statement in R

I have a function below that contains an IF statement, the error message is:我在下面有一个包含 IF 语句的函数,错误消息是:

1: In if (df == "iris1") { : the condition has length > 1 and only the first element will be used 1: 在 if (df == "iris1") { : 条件长度 > 1 并且只使用第一个元素

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"))

Create a named list and then use imap to loop over the list创建一个命名list ,然后使用imap循环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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM