【问题标题】:Creating a Function with For Loop and If Else使用 For 循环和 If Else 创建函数
【发布时间】:2022-01-08 13:27:18
【问题描述】:

您好,我应该创建一个接受三个参数的函数“check_even” (1) 'df' 一个数据框 (2) 'col_test' 测试指示列中的每一行值是偶数还是奇数。使用 for 循环和 nrow 函数。 (3) 'col_multiply' 如果 'col_test' 为偶数,则乘以 2,如果 'col_test' 为奇数,则乘以 3

  • 将结果存储在“df”调用“res”中的新列中,并返回整个数据帧“df”
  • 通过运行此代码“check_even(df_test, 'INT1', 'INT2')'来测试您的函数

df_test = data.frame(INT1 = c(1:10), INT2 = (sample(x = c(20:100),size = 10, replace = F)))
df_test

check_even = function(df, col_test, col_multiply){
  for(i in 1:nrow(df)){
    if((df[,col_test[i]] %% 2) == 0){
      df[,'res'] = (df[,col_multiply[i]] * 2)
      
    } else 
      {
        df[,'res'] = (df[,col_multiply[i]] * 3)
        
        } 
    return(df) }
}  

 
check_even(df_test, 'INT1', 'INT2')

我不断得到所有值乘以 3 的结果。我可以寻求帮助以查看我的代码有什么问题吗?

【问题讨论】:

    标签: r function for-loop if-statement


    【解决方案1】:

    使用ifelse 尝试更简单的解决方案:

    df_test = data.frame(INT1 = c(1:10), INT2 = (sample(x = c(20:100),size = 10, replace = F)))
    df_test
    
    check_even = function(df, col_test, col_multiply) {
      for(i in 1:nrow(df)){
        df$res = ifelse(df[,col_test[i]] %% 2 == 0, df[,col_multiply[i]] * 2, df[,col_multiply[i]] * 3)
        return(df)}
    }  
    
    
    check_even(df_test, 'INT1', 'INT2')
    

    【讨论】:

      【解决方案2】:

      你可以试试

      check_even = function(df, col_test, col_multiply){
        res <- c()
        for(i in 1:nrow(df)){
          if((df[i,col_test] %% 2) == 0){
            res = c(res,df[i,col_multiply] * 2)
            
          } else 
          {
            res = c(res,df[i,col_multiply] * 3)
          } 
        }
        df$res <- res
        return(df)
      }  
      
      
      
      check_even(df_test, 'INT1', 'INT2')
      
         INT1 INT2 res
      1     1   61 183
      2     2   88 176
      3     3   85 255
      4     4   95 190
      5     5   81 243
      6     6   83 166
      7     7   70 210
      8     8   37  74
      9     9   29  87
      10   10   91 182
      

      或者使用dplyr,不需要任何for循环

      library(dplyr)
      
      check_even = function(df, col_test, col_multiply){
        df %>%
          mutate(res = ifelse({{col_test}} %% 2 == 0, {{col_multiply}} * 2, {{col_multiply}} * 3))
      }  
          
      
      check_even(df_test, INT1, INT2)
      
         INT1 INT2 res
      1     1   61 183
      2     2   88 176
      3     3   85 255
      4     4   95 190
      5     5   81 243
      6     6   83 166
      7     7   70 210
      8     8   37  74
      9     9   29  87
      10   10   91 182
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-04-09
        • 1970-01-01
        • 2021-09-16
        • 1970-01-01
        • 1970-01-01
        • 2022-01-10
        • 1970-01-01
        相关资源
        最近更新 更多