[英]Writing if / ifelse function in R
I am attempting to write a function in order to create a variable (BBDR) based on the conditions of another variable (Site0) using the if function.我正在尝试编写一个函数,以便使用 if 函数根据另一个变量 (Site0) 的条件创建一个变量 (BBDR)。 I have the following code using the if function.
我有以下使用 if 函数的代码。
x1 <- (africanaDamRate$BB6-africanaDamRate$BB0)/29
x2 <- (africanaDamRate$BB6-africanaDamRate$BB0)/22
x3 <- (africanaDamRate$BB6-africanaDamRate$BB0)/34
x4 <- (africanaDamRate$BB6-africanaDamRate$BB0)/30
F1 <- function(y){
if(africanaDamRate$Site0==1){africanaDamRate$BBDR<-x1}
if(africanaDamRate$Site0==2){africanaDamRate$BBDR<-x2}
if(africanaDamRate$Site0==3){africanaDamRate$BBDR<-x3}
if(africanaDamRate$Site0==4){africanaDamRate$BBDR<-x4}
}
africanaDamRate$BBDR<-F1(y)
But when I attempt this code I receive "The condition has length greater than 1..."但是当我尝试使用此代码时,我收到“条件长度大于 1...”
I have also attempted using the ifelse function with the following code:我还尝试将 ifelse 函数与以下代码一起使用:
africanaDamRate$BBDR<-ifelse(c(africanaDamRate$Site0==1, x1, NA), c(africanaDamRate$Site0==2, x2, NA), c(africanaDamRate$Site0==3, x3, NA), c(africanaDamRate$Site0==4, x4, NA))
But get the "unused argument" error.但是得到“未使用的参数”错误。
Does anyone have any ideas of how I can do this (without subsetting)?有没有人对我如何做到这一点(没有子集)有任何想法? Thanks so much!
非常感谢!
Ryan瑞安
Your ifelse statement is wrong.你的 ifelse 语句是错误的。 It could be written like this:
可以这样写:
africanaDamRate$BBDR <- ifelse(africanaDamRate$Site0 == 1, x1,
ifelse(africanaDamRate$Site0 == 2, x2,
ifelse(africanaDamRate$Site0 == 3, x3,
ifelse(africanaDamRate$Site0 == 4, x4, NA))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.