【问题标题】:How to solve The condition has length > 1 and only the first element will be used in R [closed]如何解决条件的长度> 1,并且只有第一个元素将用于R [关闭]
【发布时间】:2018-04-06 13:12:18
【问题描述】:

当我输入这些代码时,

z<-NULL
for(i in unique(A$KCL_ID)){
  RESULT<-A[A$KCL_ID==i,]
    if(RESULT$DAYS==min(RESULT$DAYS)){
      RESULT$DATE<-"closest"
    }else{RESULT$DATE<-RESULT$BMIextraction}
z<-rbind(z,RESULT)
  }

我收到一些类似这样的错误消息:

Error in charToDate(x) : 
character string is not in a standard unambiguous format
In addition: Warning messages:
1: In if (RESULT$DAYS == min(RESULT$DAYS)) { :
  the condition has length > 1 and only the first element will be used
2: In if (RESULT$DAYS == min(RESULT$DAYS)) { :
  the condition has length > 1 and only the first element will be used
3: In if (RESULT$DAYS == min(RESULT$DAYS)) { :
  the condition has length > 1 and only the first element will be used
4: In if (RESULT$DAYS == min(RESULT$DAYS)) { :
  the condition has length > 1 and only the first element will be used

我该如何解决这个问题?

【问题讨论】:

  • if 需要一个逻辑标量;也许您正在寻找矢量化的ifelse
  • 阅读help("if")应该可以帮助您解决问题。

标签: r for-loop if-statement


【解决方案1】:

您似乎正在尝试按组进行操作。 ave() 函数对此很有帮助,尽管它的名称可能看起来并不明显。一、使用ave()分组处理行

closest <- ave(A$DAYS, A$KLS_ID, FUN = function(x) x == min(x))

这会将DAYS 拆分为KLS_ID 定义的向量,然后将FUN 应用于每个向量。当对应元素是具有相同KSL_ID 的所有行的最小值DAYS 时,closest 是一个值为TRUE 的逻辑向量。然后使用默认值创建一个新列A$DATE,并更新相关条目

A$DATE = A$BMIextraction
A$DATE[closest] <- "closest"

你原来的代码有两个问题。

似乎有“关系”,所以几天是“最接近的”。如果您想避免这些,请更新函数 x == min(x) 以解决您认为合适的关系,例如,选择标记为“最近”x == min(x) &amp; !duplicated(x == min(x)) 的第一行。

DATEBMIextraction 列似乎是一个日期,您正在尝试使用“日期”"closest" 进行更新;显然“最近”不能表示为像"06-04-2018" 这样的日期。最好简单地创建一个包含逻辑向量的列,指示该成员是最接近的,即,

A$closest <- ave(A$DAYS, A$KLS_ID, FUN = function(x) x == min(x))

【讨论】:

  • @RichScriven 是的,已更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-05
  • 2020-05-23
相关资源
最近更新 更多