【问题标题】:How to fix 'Error in if (p_change[j] == dat[i, 1]) { : missing value where TRUE/FALSE needed' in a loop?如何在循环中修复“if (p_change[j] == dat[i, 1]) { : 需要 TRUE/FALSE 的缺失值”中的错误?
【发布时间】:2019-03-31 02:27:08
【问题描述】:

我是 R 新手。我正在运行一个循环,它基本上将向量 (p_change) 中包含的值与数据框列中的值 (dat,列 IndicatorID,更具体地说)。如果 IndicatorIDp_change 中的数字一致,我希望 standardized 上的值减一(在同一行上)。 这是向量的样本 (p_change):

p_change <- c(30101,92901,92031,90630,90282,10401)

与之比较的数据框(dat)如下:

IndicatorID IndicatorName                                          AreaName             standardised variance
        <int> <chr>                                                  <chr>                       <dbl>    <dbl>
1       10401 1.04 - First time entrants to the youth justice system Hartlepool                  0.601   13478.
2       10401 1.04 - First time entrants to the youth justice system Middlesbrough               0.481   13478.
3       10401 1.04 - First time entrants to the youth justice system Redcar and Cleveland        0.773   13478.
4       10401 1.04 - First time entrants to the youth justice system Stockton-on-Tees            0.732   13478.
5       10401 1.04 - First time entrants to the youth justice system Darlington                  0.545   13478.
6       10401 1.04 - First time entrants to the youth justice system Halton                      0.353   13478.

我正在运行的 for 循环是这个:

for (i in 1:nrow(dat)) {
  for (j in 1:length(p_change)) {
    if (p_change[j]==dat[i,1]) {
      dat[i,4] <- 1-dat[i,4] # Subtraction of a unit (polarity change)
    } else {
      i = i+1
    }
  }
}

但是,在运行它之后,它会向我抛出以下错误“if (p_change[j] == dat[i, 1]) { : 需要 TRUE/FALSE 的缺失值”。我想知道您是否发现了导致错误的故障。 谢谢!

【问题讨论】:

  • (1) 请张贴数据图像:它不能被复制或搜索 (SEO),它会破坏屏幕阅读器,并且它可能不适合某些移动设备。参考:meta.stackoverflow.com/a/285557/3358272(和xkcd.com/2116)。最好给出明确的数据,例如dput(head(dat)) 的输出;可能有很多事情会导致问题,当显示为图像或在控制台上时,并非所有事情都可以识别。 (我的猜测:您的比较包含一个无效数字,请参阅例如 if (NA) 1 else 2。)

标签: r loops for-loop if-statement


【解决方案1】:

for 循环的顺序不正确。首先,代码应该循环遍历向量,然后遍历相关数据帧。

for (i in 1:length(p_change)) {
  for (j in 1:nrow(dat)) {
    if (p_change[j]==dat[i,1]) {
      dat[i,4] <- 1-dat[i,4] # Subtraction of a unit (polarity change)
    } else {
      i = i+1
    }
  }
}

【讨论】:

    猜你喜欢
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 2016-07-01
    相关资源
    最近更新 更多