也许最好将其作为两个问题提出。
较大的问题是我正在编写一个for循环(在另一个循环中),该循环将数据框架分为等于I等于I的行,或者用最新信息返回行(S)。为了澄清,for循环在一个范围内运行(1:90),并且最多没有数据(i)。为了解决这个问题,我写了一个Ifelse(IS.na(),如果是否则),尽管其他条件似乎奏效,但我正在努力编码IF。
自然,我正在提出一个简化的版本:
df$days <- c(7, 17, 20, 22, 42, 55, 55, 82, 168, 251, 308)
for(i in 1:90)
{
latest <- ifelse(is.na(df$days[i])== TRUE,
subset(df, days == min(days >=i)),
subset(df, days == i))
}
这使我想到了,中心问题。我一直在玩min(),看来我的代码有一个问题:
i = 1
df$days
[1] 7 17 20 22 42 55 55 82 168 251 308
> min(df$days >= i)
[1] 1
我的目的是返回高于i的最低价值。因此,在此示例中,那将是7。但是,最低(DF $ DAME&GT; = i)返回i。
编辑 user2974951提供了一个代码,该代码似乎已解决了中心问题(谢谢!),但是现在我的iFelse()不再按预期工作,并且正在生成没有信息的列表。
Perhaps this would be better presented as 2 questions.
The larger issue is that I'm writing a for loop (within another for loop) which subsets the dataframe into rows which are either equal to i, or return the row(s) with the latest information. For clarification's sake the for loop operates over a range (1:90) and there is no data at most iterations (i's). To account for this I've written an ifelse(is.na(),IF,ELSE), and while the ELSE condition seems to work, I'm struggling to code the IF.
Naturally, I'm presenting a simplified version:
df$days <- c(7, 17, 20, 22, 42, 55, 55, 82, 168, 251, 308)
for(i in 1:90)
{
latest <- ifelse(is.na(df$days[i])== TRUE,
subset(df, days == min(days >=i)),
subset(df, days == i))
}
Which brings me to, what I expect to be, the central issue. I've been playing around with min(), and it seems that it's here that my code has a problem:
i = 1
df$days
[1] 7 17 20 22 42 55 55 82 168 251 308
> min(df$days >= i)
[1] 1
My intention is to return the minimal value which is above i. So in this example, that would be 7. But instead, min(df$days >= i) returns i.
EDIT user2974951 provided a code which seems to have fixed the central issue (Thank you!), but now my ifelse() no longer works as intended, and is producing lists devoid of information.
发布评论
评论(2)
我认为这是做我想做的事情的一种紧凑而强大的方式。
I think this is a compact and robust way of doing what I think you're trying to do.
之所以获得1的原因是因为
df $ days&gt; = i
返回一个逻辑向量,然后将其解释为min> min
的数字(true> true
) AS 1和false
as 0):在2022-06-10创建的(v1.0.0)
as user2974951子集您的原始数据:
The reason why you get 1 is because
df$days >= i
returns a logical vector which is then interpreted as numeric formin
(TRUE
as 1 andFALSE
as 0):Created on 2022-06-10 by the reprex package (v1.0.0)
As user2974951 mentioned, you need to use this logical vector to subset your original data: