ifelse()中的多个变量分配 [英] Multiple variable assignments in ifelse()

查看:110
本文介绍了ifelse()中的多个变量分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里犯了什么错误?如果这三个语句中的任何一个为真,我试图为ab分配一些值.我正在尝试使用ifelse语句:

What mistake I am making here? I am trying to assign a and b some value if either three of the statements are true. I am trying to use the ifelse statement:

ifelse(1==1||2==2||3==3, (a<-100,b<-100), (a<-1000,b<-1000)) 

但是我得到一个错误:

错误:"ifelse(1 == 1 || 2 == 2 || 3 == 3,(a< -100,"

Error: unexpected ',' in " ifelse(1==1||2==2||3==3,(a<-100,"

按照更一般的方式,有两个变量a和b需要根据条件分配不同的值:if(x =="cat"或x =="dog"或x =="horse",那么a是100,b是200,否则a是500,b是1000)

In a more genraralized manner, there are two variables a and b that need to assigned different values depending on the conditions :if (x=="cat" or x=="dog" or x=="horse", then, a is 100 and b is 200, else, a is 500 and b is 1000)

推荐答案

回答OP很好地在评论中陈述的问题:

Answering the question nicely stated by OP in the comments:

如果(x =="cat"或x =="dog"或x =="horse",则a为100,b为200,否则a为500而b为1000)

if (x=="cat" or x=="dog" or x=="horse", then, a is 100 and b is 200, else, a is 500 and b is 1000)

if (x == "cat" || x == "dog" || x == "horse") {
  a = 100
  b = 200 
} else {
  a = 500
  b = 1000
}

我们可以使用%in%代替|做得更好-效果很好,尤其是当您需要检查更多的值时

We can do a little better using %in% instead of | - works well especially if you have even more values to check

if (x %in% c("cat", "dog", "horse")) {
  a = 100
  b = 200 
} else {
  a = 500
  b = 1000
}

ifelse是返回向量的向量化函数.如果要执行"操作,或为每个测试条件返回一个以上的值,则if(){}else{}是合适的.

ifelse is a vectorized function that returns a vector. If you want to "do" things, or return more than 1 value for each test condition, if(){}else{} is appropriate.

这篇关于ifelse()中的多个变量分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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