[英]R ifelse statement
I'm pretty new at R. I have the following data set (data frame) composed by characters:我是 R 的新手。我有以下由字符组成的数据集(数据框):
"Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y"
"Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "N" "N" "Y" "Y" "Y"
"Y" "Y" "Y" "Y" "Y" "N" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y"
"Y" "N" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "N" "Y" "Y" "Y" "Y" "Y" "Y"
"Y" "Y" "Y" "Y" "Y" "Y" "N" "Y" "Y" "Y" "N" "Y" "Y" "Y" "Y" "Y" "Y"
"Y" "Y" "Y" "N" "Y" "Y" "Y" "Y" "N" "Y" "Y" "Y" "Y" "N" "Y" "Y" "Y"
"Y" "Y" "Y" "Y" "Y" "Y" "N" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y"
"Y" "Y" "Y" "Y" "Y" "Y" "N" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y"
"Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y"
"Y" "Y" "N" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y"
"Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y"
"Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y" "Y"
"Y" "Y" "Y" "Y" "Y" "Y" "N" "Y" "Y" "Y" "Y" "Y" "Y" "N" "Y" "Y"
and I want to replace Y
with 1 and N
with 0. Thus I'm using the following expression:我想用 1 替换Y
,用 0 替换N
因此我使用以下表达式:
ifelse(Dataset$A=="N",Dataset$A<-0,Dataset$A<-1)
Although, the result from the ifelse
function is correct but when printing the variable I m getting this:虽然, ifelse
函数的结果是正确的,但是在打印变量时我得到了这个:
"1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1"
"1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1"
"1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1"
"1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1"
"1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1"
"1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1"
"1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1"
"1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1"
Do you have any hint why?你有什么提示吗?
Add another variable B to dataset and use ifelse function where you get 0 for "N"and 1 for "Y" values将另一个变量 B 添加到数据集并使用 ifelse 函数,其中“N”值为 0,“Y”值为 1
Dataset$B <- ifelse(Dataset$A=="N",0,1)
or you can use ifelse function on same variable as或者您可以在相同的变量上使用 ifelse 函数
Dataset$A <- ifelse(Dataset$A=="N",0,1)
你也可以这样做:
Dataset$A <- (Dataset$A=="Y")*1
ifelse can work, but an other option is to use the switch() function: ifelse 可以工作,但另一种选择是使用 switch() 函数:
vec <- c("Y","Y","Y","N","N","Y")
sapply(vec, switch, "Y"=1,"N"=0)
it does what you want, but for vectors of size 1. You then sapply it through all of your elements.它可以满足您的需求,但对于大小为 1 的向量。然后您将其应用于所有元素。
The good thing about switch function (that ifelse doesn't do) is that you can use as many substitution as you want ("A"=1, "B"=2, "C"=3, etc...), switch 函数的好处(ifelse 不这样做)是您可以使用任意数量的替换(“A”=1、“B”=2、“C”=3 等...),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.