gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:52:01 25 4
gpt4 key购买 nike

我想要虚拟代码,即为“物种”列创建标志变量。

我编写了以下代码:

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)

我收到警告:

Warning messages:
1: In if (categorical_preds == "setosa") { :
the condition has length > 1 and only the first element will be used
2: In if (categorical_preds == "versicolor") { :
the condition has length > 1 and only the first element will be used
3: In if (categorical_preds == "virginica") { :
the condition has length > 1 and only the first element will be used

然后我将代码更改为:

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)

这次没有警告,但新的虚拟变量始终为 0。

下一步我想避免硬编码,所以我写了

create_dummies <- function(data, categorical_preds){
catvar <- (unique(categorical_preds))

for (i in 1:length(catvar)){
iris[catvar[i]] <- ifelse(iris$Species == catvar[i],1,0)
}
return(data)
}
create_dummies(iris,iris$Species)
<小时/>

这有什么问题吗?

问题:

  1. 为什么这两个版本的代码不起作用?

  2. if(){} 有什么区别和ifelse() R 中的函数?

  3. ifelse() ,如果条件是true ,我怎样才能执行多个操作?
    示例:ifelse(categorical_preds == "setosa",data$setosa_flg <- 1 print(iris$Species),data$setosa_flg <- 0) .

最佳答案

警告消息:

  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
}

关于r - if() 和 ifelse() 函数之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22433704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com