【问题标题】:Using a for loop to count negative values and add to new column使用 for 循环计算负值并添加到新列
【发布时间】:2017-06-14 02:30:38
【问题描述】:

我对 R 很陌生,我想在 R 中尝试不同的东西。 我创建了一个数据框,我想使用 for 循环来选择负值的数量。我想将此数字添加到我的数据框中的新列中。我知道有更简单的方法可以做到这一点,但我真的很想掌握 R 中的循环。 你们有人对我有什么建议吗?我将在下面发布我的数据框。

newframe

提前致谢!

【问题讨论】:

    标签: r for-loop select dataframe negative-number


    【解决方案1】:

    是的,显然有更简单的方法可以做到这一点,但我会给你一些关于循环的建议。 首先,让我们创建一个额外的列:

    nf=data.frame(newframe,neg=rep(NA))   #I called the column "neg" 
    

    其次,你必须定义循环开始和结束的范围:

     for (i in 1:length(newframe[,1])) {
    
    }
    

    评论:我直接写了 length(newframe[,1]) 而不是 500。最好指出与您正在使用的对象相关联的东西。例如,如果您向 data.frame 添加更多行,它将被处理并且您的循环仍然可以工作。

    在循环内部,如果您只想要负数,则必须使用 IF 条件来获取它们: (我们在这里处理数据框的第一列,但您也可以执行“for”循环来处理每一列)

     if(newframe[i,1]<=0){
      nf$neg[i]=newframe[i,1]
      }
    

    那么你就有了第一列的解决方案!我让你一个人做第二栏:)

    【讨论】:

      【解决方案2】:

      首先获取数据集的行数和列数:

      nr = NROW(newframe); # you can use the lowercase variant as well or the dim command
      nc = NCOL(newframe);
      

      然后循环遍历行和列:

      response = 0;
      for(ir in 1:nr) { // cycle through rows
      
          for(ic in 1:nc) { // cycle through columns
              response = response + ifelse(newframe[ir, ic]<0, 1, 0);
          }
      
      }
      

      response 变量包含数据集的负值数量。

      循环的工作方式类似于 for-each 语句,让我们考虑外部 for 循环:ir 将获取由命令 1:nr 生成的系列的所有值(即 1、@987654327 @, ... nr)。

      另一个例子是

      x = c("a", "b", "c");
      for(v in x) { 
          cat(v, "\n"); 
      }
      

      你会得到输出

      > a
      b
      c
      

      这意味着您可以通过使用单个 for 循环来获得相同的结果:

      response = 0;
      for(v in unlist(newframe)) { # you need to un-list the dataframe otherwise you would cycle through the columns...
          response = response + ifelse(v<0, 1, 0);
      }
      

      如果您愿意,您可以随时从 for 循环切换到 while 循环:

      response = 0;
      ir = 1;
      while(ir<=nr) { // cycle through rows
      
          ic = 1;
          while(ic<=nc) { // cycle through columns
              response = response + ifelse(newframe[ir, ic]<0, 1, 0);
              ic = ic + 1;
          }
          ir = ir + 1;
      
      }
      

      希望我已经回答了你的问题:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-01
        • 2016-01-02
        相关资源
        最近更新 更多