【问题标题】:Create a "for" loop for columns and rows in R为 R 中的列和行创建一个“for”循环
【发布时间】:2022-01-22 04:59:07
【问题描述】:

我有这个数据框:

a <- c(2,5,90,77,56,65,85,75,12,24,52,32)
b <- c(45,78,98,55,63,12,23,38,75,68,99,73)
c <- c(77,85,3,22,4,69,86,39,78,36,96,11)
d <- c(52,68,4,25,79,120,97,20,7,19,37,67)
e <- c(14,73,91,87,94,38,1,685,47,102,666,74)

df <- data.frame(a,b,c,d,e)

我需要在 R 中循环转换以下脚本: 变量“f”表示我的数据框(“df”)的一列,我需要它在循环中的范围为 1 到 5(即我的数据框 df 中的列数)。此外,循环必须一次考虑三行。 这样,在每个循环中,运行脚本我都会为每个考虑的“f”找到一个“cdf_min”。

脚本:

f <- 1
x <- (df[1:3,f])
y <- (df[1:3,-f])
dif_2 <- (x - y)^2
summ <- colSums(dif_2)
summa <- t(as.matrix(summ))
cmin <- which(summa == apply(summa,1,min))
cdf_min <- 
  if (f <= cmin){
    cmin+1
  } else{cmin}

我希望我很清楚。 谢谢大家帮助我!

【问题讨论】:

    标签: r loops for-loop


    【解决方案1】:

    要创建for 循环,您可以在sequence 上迭代列上的f,并将其用作结果向量cdf_min[f] 的索引。

    cdf_min <- rep(NA, ncol(df))  ## initialize results vector
    
    for (f in seq(ncol(df))) {
      x <- df[1:3, f]
      y <- df[1:3, -f]
      dif_2 <- (x - y)^2
      summ <- colSums(dif_2)
      summa <- t(as.matrix(summ))
      cmin <- which(summa == apply(summa, 1, min))
      cdf_min[f] <- 
        if (f <= cmin) {
          cmin + 1
        } else { 
          cmin
        }
    }
    
    cdf_min
    # [1] 5 5 4 3 2
    

    编辑

    为了还循环一组行,我们可以使用Map 创建,我们首先初始化一个矩阵,其行数对应于行集的长度,以及我们迭代的相同列数。之后,我们创建一个外部for 循环,它迭代行集的sequence,类似于内部循环。为了对数据框进行子集化,我们使用序列值作为索引从行集中进行选择。

    R <- Map(`+`, list(2:4), 0:8) 
    cdf_mat <- matrix(NA, length(R), ncol(df))  ## initialize results matrix
    
    for (r in seq(R)) {
      for (f in seq(ncol(df))) {
        x <- df[R[[r]], f]
        y <- df[R[[r]], -f]
        dif_2 <- (x - y)^2
        summ <- colSums(dif_2)
        summa <- t(as.matrix(summ))
        cmin <- which(summa == apply(summa, 1, min))
        cdf_mat[r, f] <- 
          if (f <= cmin) {
            cmin + 1
          } else { 
            cmin
          }
      }
    }
    
    cdf_mat
    #       [,1] [,2] [,3] [,4] [,5]
    # [1,]    5    5    4    3    2
    # [2,]    2    1    4    3    1
    # [3,]    5    5    1    1    1
    # [4,]    3    5    1    1    2
    # [5,]    3    3    1    3    1
    # [6,]    4    3    2    1    1
    # [7,]    4    3    2    1    1
    # [8,]    4    3    2    1    2
    # [9,]    4    3    1    1    2
    

    【讨论】:

    • 非常感谢!例如,如果我想在循环中创建一个循环,该循环随后考虑第 2:4、3:5、4:6、...、10:12 行,我该怎么办?
    • 不客气@RobSe,请查看编辑。
    猜你喜欢
    • 2021-09-14
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多