【问题标题】:How to create a function which depending in a conditions delays a nested loop or not如何创建一个根据条件延迟嵌套循环或不延迟的函数
【发布时间】:2020-08-09 14:42:42
【问题描述】:

我需要创建一个 函数,它依赖于 2 个变量和一个表(?)(x,y,表)。首先,该函数需要遍历表中的每一行,并且依赖于“X”列值(1 或 0)采取不同的操作:

当 x 列 = 1 时,复制行 'y' 次。然后在嵌套循环中创建一列,从 1 到 y 计算行被复制的次数。

当 x 列 = 0 时,保持该行不变。

输入的一个例子是

输出将是

我尝试编写下一个代码,但老实说我不太擅长循环。

    My_function <- function(x,y,table) {

      for (i in 1:nrow(table)) {

        if(table[,which(colnames(table) = as.character(x)] == 1){
          dummy = table[i,]
          final_dummy = NULL

          for(j in 1:dummy$y){
            dummy_2 = dummy
            final_dummy = rbind(final_dummy,dummy_2)
                                                     }
        } else if(table[,which(colnames(table) = as.character(x)] == 0){
              table[i,] 
      }
    }
    }

【问题讨论】:

  • 欢迎来到 SO 和 R。感谢您提供输入和输出期望的图像。如果您将输入数据包含在数据框格式中,这将有助于回答者,例如df

标签: r function loops nested conditional-statements


【解决方案1】:

你也可以使用:

library(tidyverse)
df <- tibble(col = c(letters[1:3]), x = c(1, 0, 1), y = c(2, 3, 4))

df %>% 
  mutate(uncY = if_else(x == 0, 1, y)) %>% 
  uncount(uncY, .id = "id")

# A tibble: 7 x 4
  col       x     y    id
  <chr> <dbl> <dbl> <int>
1 a         1     2     1
2 a         1     2     2
3 b         0     3     1
4 c         1     4     1
5 c         1     4     2
6 c         1     4     3
7 c         1     4     4

【讨论】:

    【解决方案2】:

    你可以把函数写成:

    My_function <- function(data) {
      out <- data[with(data, rep(seq_along(col), pmax(colx * coly, 1))), ]
      rownames(out) <- NULL
      out$num <- with(out, ave(colx, col, FUN = seq_along))
      return(out)
    }
    

    并称之为

    My_function(df)
    
    #  col colx coly num
    #1   a    1    2   1
    #2   a    1    2   2
    #3   b    0    3   1
    #4   c    1    4   1
    #5   c    1    4   2
    #6   c    1    4   3
    #7   c    1    4   4
    

    数据

    df <- data.frame(col = letters[1:3], colx = c(1, 0, 1), coly = c(2, 3, 4))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-11
      • 2016-04-13
      • 2012-04-20
      • 1970-01-01
      • 1970-01-01
      • 2014-07-22
      • 2019-09-27
      • 2015-05-17
      相关资源
      最近更新 更多