if循环中的ifelse不会产生所需的输出 [英] Ifelse in a for loop not yielding desired output

查看:109
本文介绍了if循环中的ifelse不会产生所需的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含2列的数据集,即time(Ti)和counter(Co)。每当计数器为1时,我应该计算行时间和之前行时间之间的时间差。

I have a dataset with 2 columns namely, "time(Ti)" and "counter(Co)". Whenever the counter is 1 , I am supposed to calculate time difference between that "row time" and previous "row time" .

为了达到上述要求,我正在使用以下逻辑

To achieve the above requirement, I am using the below logic

for (i in 1:length(file1$counter))
{  
  n1 <-  ifelse(file1$counter==1,(file1$TIME[(i)] - file1$TIME[(i-1)]),0)
}

但我得到的标准输出为 0 0 2 2 2 2 2 0 0 0 0 0 0 2 2 2 2 2 0 0 而不是 0 0 2 1 4 1 4 0 0 0 0 0 0 2 2 2 2 2 0 0
此外,n1默认显示为时间序列,Start = 1,End = 20,
Frequency = 1.

But I am getting a standard output as 0 0 2 2 2 2 2 0 0 0 0 0 0 2 2 2 2 2 0 0 instead of 0 0 2 1 4 1 4 0 0 0 0 0 0 2 2 2 2 2 0 0 Also the n1 is by default shown as Time Series with Start = 1, End = 20 and Frequency = 1.

推荐答案

如docendo discimus所述, ifelse 是R中的向量化操作。您可以省略 for 循环以便得到想要的结果。这是一个例子:

As docendo discimus noted, ifelse is a vectorized operation in R. You can omit the for loop in order to get the desired result. Here's an example:

filename   = c("aa", "bb", "cc") 
counter    = c(1, 2, 3) 
df = data.frame(filename, counter) 
df$n1 <- ifelse(df$counter == 1, "one", "other")

这给了我们一个更新的 df : / p>

Which gives us an updated df of:

  filename counter    n1
1       aa       1   one
2       bb       2 other
3       cc       3 other

这篇关于if循环中的ifelse不会产生所需的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆