【问题标题】:Function with IF ELSE doesn't work带有 IF ELSE 的功能不起作用
【发布时间】:2018-08-29 14:34:05
【问题描述】:

我有一个简单的函数:

new_function <- function(x)
 {
letters <- c("A","B","C")
new_letters<- c("D","E","F")

 if (x %in% letters) {"Correct"}
 else if (x %in% new_letters) {"Also Correct"}
 else   {x} 
 }

我用字母创建dataframe

df <- as.data.frame(LETTERS[seq( from = 1, to = 10 )])
names(df)<- c("Letters")

我想在dataframe上应用这个函数:

  df$result <- new_function(df$Letters)

而且不起作用(函数只写“正确”)

我收到此警告:

警告信息: 在 if (x %in% 个字母) { : 条件的长度 > 1,并且只使用第一个元素

【问题讨论】:

  • 如果长度大于1,用ifelse代替if/else
  • and if 语句将评估括号之间的部分是否为 TRUE。如果您将一个字母向量传递给if (x %in% letters) {"Correct"},这将返回一个TRUEFALSE 值的向量。每个字母一个。
  • @Soren Stilling Christensen:当有人回答您的问题时,请考虑投票或接受答案。

标签: r function if-statement


【解决方案1】:

你可以使用lapply:

df$result <- lapply(df$Letters,new_function)

输出:

df
   Letters       result
1        A      Correct
2        B      Correct
3        C      Correct
4        D Also Correct
5        E Also Correct
6        F Also Correct
7        G            7
8        H            8
9        I            9
10       J           10

【讨论】:

    【解决方案2】:

    我会按照@akrun 的建议用ifelse 重写您的new_functionas.characterx 转换为字符,以防它是一个因素:

    new_function <- function(x){
      ifelse(x %in% c("A","B","C"), "Correct",
             ifelse(x %in% c("D","E","F"), "Also Correct", as.character(x)))
    }
    
    df$result <- new_function(df$Letters)
    

    或与case_when 来自dplyr

    library(dplyr)
    
    new_function <- function(x){
      case_when(x %in% c("A","B","C") ~ "Correct",
                x %in% c("D","E","F") ~ "Also Correct",
                TRUE ~ as.character(x))
    }
    
    df %>%
      mutate(result = new_function(Letters))
    

    结果:

       Letters       result
    1        A      Correct
    2        B      Correct
    3        C      Correct
    4        D Also Correct
    5        E Also Correct
    6        F Also Correct
    7        G            G
    8        H            H
    9        I            I
    10       J            J
    

    数据:

    df <- as.data.frame(LETTERS[seq( from = 1, to = 10 )])
    names(df)<- c("Letters")
    

    【讨论】:

      猜你喜欢
      • 2016-02-25
      • 1970-01-01
      • 2022-11-29
      • 2011-05-05
      • 2017-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多