R if()和ifelse()函数之间的区别

R if()和ifelse()函数之间的区别,r,if-statement,R,If Statement,我想要虚拟代码,即为列种类创建标志变量 我编写了以下代码: create_dummies <- function(data, categorical_preds){ if (categorical_preds == "setosa"){data$setosa_flg <- 1} else {data$setosa_flg <- 0} if (categorical_preds == "versicolor"){data$versicolor_flg &l

我想要虚拟代码,即为列种类创建标志变量

我编写了以下代码:

create_dummies <- function(data, categorical_preds){
    if (categorical_preds == "setosa"){data$setosa_flg <- 1}
    else {data$setosa_flg <- 0}
    if (categorical_preds == "versicolor"){data$versicolor_flg <- 1}
    else {data$versicolor_flg <- 0}
    if (categorical_preds == "virginica"){data$virginica_flg <- 1}
    else {data$virginica_flg <- 0}
    return(data)
}
create_dummies(iris,iris$Species)
然后我将代码更改为:

create_dummies <- function(data, categorical_preds){
    ifelse(categorical_preds == "setosa",data$setosa_flg <- 1,data$setosa_flg <- 0)
    ifelse(categorical_preds == "versicolor",data$versicolor_flg <- 1,data$versicolor_flg <- 0)
    ifelse(categorical_preds == "virginica",data$virginica_flg <- 1,data$virginica_flg <- 0)

    return(data)
}
create_dummies(iris,iris$Species)

create_dummies
iris$Species
是一个向量。
if
语句是设计为仅在标量布尔条件下工作的控制语句。在R中,当您将向量与字符串进行比较时,输出是一个布尔向量,告知向量的每个元素是否等于字符串。

警告消息:

  the condition has length > 1 and only the first element will be used
告诉您在
if
条件中使用向量等同于使用其第一个元素:

[if (v == 1)] ~ [if (v[1] == 1)] ## v here is a vector
您应该使用矢量化的
ifelse
。例如,您可以这样编写您的条件:

create_dummies<-function(data, categorical_preds){
  ## here I show only the first condition 
  data$setosa_flg <-
       ifelse (categorical_preds=="setosa",1,0)
  data
}

create\u dummies
If-else
应在构建函数时使用,以在给定的密码为true(一个条件,长度==1)时运行给定函数的某些部分
ifelse
在转换data.frame时应使用

有关
的帮助(如果有)

cond长度为一个非NA的逻辑向量。长度条件 接受大于1的警告,但仅接受第一个警告 元素被使用。如果可能,其他类型强制为逻辑类型, 忽略任何类

为此(如果向量是因子),可以使用model.matrix创建虚拟变量

mat<-model.matrix(~iris$Species-1)
mat<-as.data.frame(mat)
names(mat)<-unique(iris$Species)

> str(mat)
'data.frame':   150 obs. of  3 variables:
 $ setosa    : num  1 1 1 1 1 1 1 1 1 1 ...
 $ versicolor: num  0 0 0 0 0 0 0 0 0 0 ...
 $ virginica : num  0 0 0 0 0 0 0 0 0 0 ...

matif(分类preds==“setosa”){data$setosa_flgI我想你应该添加一些数据来重现你的问题。我们在这里假设e
categorical_preds
与你的数据列长度相同。iris是R中内置的数据集。我不确定我是否正确理解了这个问题。这是有效的。data$setosa_flgy你应该阅读
ifelse
ifelse的gelp(测试,是,否)
。您应该返回一个值,而不是分配它。在这里
(categorical_preds==“setosa”,1,0)
,返回一个一的向量(循环更改1在一的向量中,更改0在零的向量中)。
create_dummies<-function(data, categorical_preds){
  ## here I show only the first condition 
  data$setosa_flg <-
       ifelse (categorical_preds=="setosa",1,0)
  data
}
mat<-model.matrix(~iris$Species-1)
mat<-as.data.frame(mat)
names(mat)<-unique(iris$Species)

> str(mat)
'data.frame':   150 obs. of  3 variables:
 $ setosa    : num  1 1 1 1 1 1 1 1 1 1 ...
 $ versicolor: num  0 0 0 0 0 0 0 0 0 0 ...
 $ virginica : num  0 0 0 0 0 0 0 0 0 0 ...