[英]“the condition has length > 1 and only the first element will be used” error
[英]Error of “In if (x == 1) { … : the condition has length > 1 and only the first element will be used”
我正在尝试计算data.frame中某些列的平均值和sd。 我运行以下循环:
calculations <- by(dataset, dataset$id, function (x)
{
if(x == 1)
{
c(mean(x$Var1),mean(x$Var2))
print("Cannot take sd, number of obs is equal to 1")
}
else(x > 1)
{
c(mean(x$Var1), mean(x$Var2), sd(x$Var1), sd(x$Var2))
}
#return(c(mean(x$Var1), mean(x$Var2), sd(x$Var1), sd(x$Var2)))
})
我得到的输出是:
dataset$id: 1
[1] 0.3961182 3.8605641 1.0251303 2.6779033
--------------------------------------------------------------------------
dataset$id: 2
[1] 0.1656521 3.7565732 0.8687900 2.2305298
--------------------------------------------------------------------------
dataset$id: 3
[1] -0.3831954 4.0803145 1.3875692 2.1146944
--------------------------------------------------------------------------
dataset$id: 4
[1] 0.6719857 4.7523648 0.2001029 1.3715562
--------------------------------------------------------------------------
dataset$id: 5
[1] 0.01666328 3.18141270 0.98473329 1.76379804
--------------------------------------------------------------------------
dataset$id: 6
[1] 0.2542346 4.6464406 1.1077001 2.4604031
--------------------------------------------------------------------------
dataset$id: 7
[1] -0.1826018 5.6737908 NA NA
直到dataset $ id40。在我的循环中,我希望NA打印“无法取sd”。 当我运行代码时,我只会得到以下错误消息:
Warning messages:
1: In if (x == 1) { ... :
the condition has length > 1 and only the first element will be used
2: In if (x == 1) { ... :
the condition has length > 1 and only the first element will be used
3: In if (x == 1) { ... :
the condition has length > 1 and only the first element will be used
有谁知道如何解决这一问题?
很明显从
by(dataset, dataset$id, function (x) ....
x
接受datatset
行的子集。 然后您的代码说
if (x == 1)
并且由于x
是数据帧,您希望通过测试数据帧是否等于1来实现什么?
如果要测试行数,请考虑
if (nrow(x) > 1L)
作为测试并翻转if
和else
分支或做的内容
if (nrow(x) < 2L) ## or
if (nrow(x) == 1L)
如果您不想翻转分支。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.