循环使用if语句对数字进行分类 [英] Loops with if statements classifying numbers

查看:282
本文介绍了循环使用if语句对数字进行分类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个循环的麻烦。我的意图是循环将看到值下降的位置并给该值另一个名称。这是我想要做的一个例子:

I am having trouble with a loop I am creating. My intention is that the loop will see where a value falls and give that value another name. Here is an example of what I am trying to do:

a<-rnorm(10,0,1)
b<-rnorm(10,0,1)

testing<-data.frame(a,b)

testing2<-testing
for (i in 1:nrow(testing2)){
  for (j in 1:ncol(testing2)){
    if (testing2[i,j]>1) testing2[i,j]<-"More"
    else if (testing2[i,j]<(-1)) testing2[i,j]<-"Less"
    else testing2[i,j]<-"Same"
  }
}

当我查看testing2并将其与测试,它与它应该做的不匹配。 更多似乎有效,但它在少和相同之间混淆了。

When I look at testing2 and compare it to testing, it does not match what it should be doing. "More" seems to work, but it gets mixed up between "Less" and "Same".

推荐答案

不需要(嵌套)循环,使用vectorised ifelse

No need for a (nested) loop, use the vectorised ifelse instead:

testing = ifelse(testing > 1, 'More', ifelse(testing < -1, 'Less', 'Same'))

这篇关于循环使用if语句对数字进行分类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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