简体   繁体   English

在R的ifelse()中使用复合不等式

[英]Using compound inequalities within ifelse() in R

I am trying to create a new factor variable that is conditional based on a numeric variable within my dataframe. 我正在尝试创建一个新的因子变量,该变量是基于数据框内的数字变量而定的。 my ifelse argument works perfectly when I supply it a single inequality, but for the two categories that require a compound inequality, it doesn't work. 当我提供一个不等式时,我的ifelse参数可以完美地工作,但是对于需要复合不等式的两个类别,它不起作用。 I'm familiar with logic and conditions in other languages, and I'm thinking just my syntax is off? 我熟悉其他语言的逻辑和条件,并且我认为我的语法已关闭?

Also, there seems to be times when you can use '&' and times to use '&&'. 另外,似乎有时可以使用“&”,有时也可以使用“ &&”。 I'm used to always using '&&', so what is the difference here? 我习惯总是使用'​​&&',所以这里有什么区别?

data$bin<-as.factor(ifelse(data$internet<=2.3225,"one",
                      ifelse(data$internet>2.3225 && data$internet<=4.425,"two",
                      ifelse(data$internet>4.425 && data$internet<=6.5275,"three",
                      ifelse(data$internet>6.5275,"four",NA)))))

&& doesn't vectorize. &&不会向量化。 Unless you want to compare a single element to a single element, you should use & . 除非要将单个元素与单个元素进行比较,否则应使用&

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM