我是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"
我希望将Y
替换为1,将N
替换为0.因此,我使用以下表达式:
ifelse(Dataset$A=="N",Dataset$A<-0,Dataset$A<-1)
虽然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"
你有什么提示吗?
答案 0 :(得分:2)
将另一个变量B添加到数据集并使用ifelse函数,其中0为&#34; N&#34; 1为&#34; Y&#34;价值
Dataset$B <- ifelse(Dataset$A=="N",0,1)
或者您可以在与
相同的变量上使用ifelse函数Dataset$A <- ifelse(Dataset$A=="N",0,1)
答案 1 :(得分:1)
你也可以这样做:
Dataset$A <- (Dataset$A=="Y")*1
答案 2 :(得分:1)
ifelse可以工作,但另一个选择是使用switch()函数:
vec <- c("Y","Y","Y","N","N","Y")
sapply(vec, switch, "Y"=1,"N"=0)
它可以满足您的需求,但适用于大小为1的矢量。然后,您可以通过所有元素进行调整。
关于切换功能(ifelse不做)的好处是你可以根据需要使用尽可能多的替换(&#34; A&#34; = 1,&#34; B&#34; = 2,&#34; C&#34; = 3,等等......),