在R中使用ifelse [英] Using ifelse in R
问题描述
我正在尝试使用编译以下语句,如果
和 ifelse
。示例数据是试用版x,y和z是试用列。)
I am trying to code the following statement in R with if
and ifelse
.The sample data is trial and x,y,and z are columns of trial).
要编码的语句
if (x>0) {
if (y>0) {
l=2
}else{
l=5
}
if (z>0) {
m=l+2
}else{
m=5
}
}
使用ifelse的R代码
trial$l<-with(trial, ifelse((x>0 &y>0),2,ifelse((x>0 &y<=0),5,???)))
trial$m<-with (trial,ifelse((x>0 &z>0),l+2,ifelse((x>0 &z<=0),5,???)))
其中, ???
指定根据上述语句没有值。换句话说,对于 x< 0和y
,没有值。
where, ???
specifies that there are no values according to the above statement. In other words for x<0 and y
there are no values.
接下来,我使用组合如果和ifelse看起来有效:
if(trial$z>0){
trial$l<-with(trial, ifelse(y>0,2,5))
trial$m<-with(trial, ifelse(z>0,l+2,5))
}
这段代码还可以,但是有一条警告信息(因为 z
是列向量)
This code is ok but there is a warning message (since z
is a column vector)
In if (trial$z>0){
the condition has length>1 and only the first element will be used
我想只关注使用 ifelse
因为我只处理向量。但是,我在这方面没有运气。有什么想法吗?
I want to focus only on using ifelse
since I am dealing with only vector. But, I have no luck in this regard. Any idea?
推荐答案
我会用转换
两次,例如:
trial <- data.frame(x=c(-1,1,2),y=c(1,-2,3),z=c(1,-5,5))
trial <- transform(trial,l = ifelse(x>0,ifelse(y > 0,2,5),NA))
transform(trial,m = ifelse(x>0,ifelse(z>0,l+2,5),NA))
x y z l m
1 -1 1 1 NA NA
2 1 -2 -5 5 5
3 2 3 5 2 4
请注意,我为案例x<分配了NA。你可以使用这样的一个变换,例如:
Note that I assign NA for case x < 0. You can use a one transform like this for example:
trial <- data.frame(x=c(-1,1,2),y=c(1,-2,3),z=c(1,-5,5))
transform(trial,l <- ifelse(x>0,ifelse(y > 0,2,5),NA),
m = ifelse(x>0,ifelse(z>0,l+2,5),NA))
x y z c.NA..5..2. m
1 -1 1 1 NA NA
2 1 -2 -5 5 5
3 2 3 5 2 4
但我个人更喜欢第一个可读性,除了你需要改变列名这一事实。
But personally I would prefer the first one for readability besides the fact you need maybe change column names.
这篇关于在R中使用ifelse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!