【问题标题】:for loop, new column, length > 1, in Rfor循环,新列,长度> 1,在R中
【发布时间】:2017-06-30 06:22:17
【问题描述】:

我做了一些搜索,但找不到与我的问题完全一样的东西。我之前已经多次完成几乎完全相同的循环,除了它通常更像是“只要你有 Y(某个其他因素)就使 X(一个因素)”。

这是我的代码:

 for(i in 1:nrow(age_cont)){
      if(age_cont$Choice[i] == 1){
        age_cont$Rank[i] = "Never"
      }
      else if(age_cont$Choice[i] == 2){
        age_cont$Rank[i] = "Sometimes"
      }
      else if(age_cont[i] == 3){
        age_cont$Rank[i] = "Frequently"
      }
      else {
        age_cont$Rank[i] = "Always"
      }
    }

但我收到此错误:

> Error in `[.data.frame`(age_cont, i) : undefined columns selected
In addition: Warning messages:
1: In if (age_cont[i] == 3) { :
  the condition has length > 1 and only the first element will be used
2: In if (age_cont[i] == 4) { :
  the condition has length > 1 and only the first element will be used
3: In if (age_cont[i] == 3) { :
  the condition has length > 1 and only the first element will be used
4: In if (age_cont[i] == 4) { :
  the condition has length > 1 and only the first element will be used
> 

Choice 变量是序数 (1-4),我正在尝试创建一个与之平行的新列,但使用名称而不是数字。我尝试将 Choice 变量更改为一个因子并重新运行循环,甚至尝试简单地将每个数字重命名为一个名称(在同一列中),但这也不起作用。

有什么想法吗?

【问题讨论】:

    标签: r loops for-loop


    【解决方案1】:

    好像一行有错误

       else if(age_cont[i] == 3){
    

    我想你的意思

       else if(age_cont$Choice[i] == 3){  
    

    这应该解释错误消息。

    【讨论】:

    • 是的,但仍然没有得到我的排名列。对每个人都“永远”。
    • 顺便说一句,在else if 之前,必须在同一行中有一个结束},如} if else (cond) {。除此之外,从你的问题中我看不出有什么问题。
    • 我认为我的回答解决了您提到的错误,并解决了您提出的问题。如果您现在有不同的问题,请将其作为不同的问题与错误消息等一起发布。
    【解决方案2】:

    这是一个答案,它允许您通过与一个为您提供排名的表进行连接来删除 for 循环和几个 ifs。我做一个左连接,然后填充 na 以模仿 else 子句。

    library(tibble)
    library(dplyr)
    library(tidyr)
    
    set.seed(1)
    df <- tibble(Choice = sample(1:4, 10, replace = TRUE))
    
    transco <- tribble( ~Choice, ~Rank,
    1, "Never",
    2, "Sometimes",
    3, "Frequently")
    
    df %>% left_join(transco, by = "Choice") %>%
        replace_na(list(Rank = "Always"))
    # A tibble: 10 x 2
       Choice       Rank
        <dbl>      <chr>
    1       2  Sometimes
    2       2  Sometimes
    3       3 Frequently
    4       4     Always
    5       1      Never
    6       4     Always
    7       4     Always
    8       3 Frequently
    9       3 Frequently
    10      1      Never
    

    【讨论】:

      【解决方案3】:

      随处使用

      age_cont$Choice[i] %in% #your_number
      

      而不是

      age_cont$Choice[i] == #your_number
      

      另外,将age_cont[i] == 3 更改为age_cont$Count[i] %in% 3

      这应该可以解决您的问题。

      【讨论】:

        猜你喜欢
        • 2023-01-25
        • 2021-08-27
        • 1970-01-01
        • 1970-01-01
        • 2014-07-24
        • 1970-01-01
        • 2013-07-13
        • 2021-12-19
        • 1970-01-01
        相关资源
        最近更新 更多