Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 我正在尝试使用if-else函数生成一个算法_R_If Statement - Fatal编程技术网

R 我正在尝试使用if-else函数生成一个算法

R 我正在尝试使用if-else函数生成一个算法,r,if-statement,R,If Statement,我正在尝试使用if-else进行一些计算,但我可以得到: 我从一个模型中获得了数据,但是这个模型往往高估或低估了结果,这取决于总的结果。 我举一个简单的例子: d <- c(2,2,12,10, 24,30,50,55,60) e <- c("red", "white", "red") car <- data.frame(d,e) names(car) <- c("carro","Color") # variable names if(car$carro < 10

我正在尝试使用if-else进行一些计算,但我可以得到:

我从一个模型中获得了数据,但是这个模型往往高估或低估了结果,这取决于总的结果。 我举一个简单的例子:

d <- c(2,2,12,10, 24,30,50,55,60)
e <- c("red", "white", "red")
car <- data.frame(d,e)
names(car) <- c("carro","Color") # variable names

if(car$carro < 10){
car$carro <- car$carro * 0.5 ##50%
} else {
if((car$carro> 10) && (car$carro < 30)){
car$carro <- car$carro * 0.9 #90%
} else {
if(car$carro >30) {
car$carro <- car$carro * 1.50 #150%
} 
}
}

d您在R控制台中看到任何输出了吗

在我的电脑上,它显示:

    Warning message:
    In if (car$carro < 10) { :
      the condition has length > 1 and only the first element will be used
警告消息:
如果(车$carro<10){:
条件的长度大于1,并且只使用第一个元素

基本上,
car$carro
是一个与
d
相等的列表。因为R在将列表与数字进行比较时不知道如何输出真/假,所以它可能使用第一个列表元素2与10进行比较,并从2<10开始输出真。然后它只需将
car$carro
中的每个元素乘以0.5。

As@user13534 already说你在比较一个列表和一个数字。下面是我的方法:

d <- c(2,2,12,10, 24,30,50,55,60)
e <- c("red", "white", "red")
car <- data.frame(d,e)
names(car) <- c("carro","Color") # variable names

car$carro <- lapply(car$carro, function(x) ifelse(x < 10, x * 0.5, ifelse(x < 30 && x > 10, x * 0.9, x * 1.5)))
car

  carro Color
1     1   red
2     1 white
3  10.8   red
4    15   red
5  21.6 white
6    45   red
7    75   red
8  82.5 white
9    90   red

d在帖子中,条件不清楚。例如,
car$carro<10
(car$carro>10)和(car$carro<30)
car$carro>30
不包括“carro”为10或30的情况。我假设第一个条件是
car$carro<10
,第二个条件是
(car$carro>=10)和(car$car<30)
和第三个as
car$carro>=30

无需使用
ifelse
即可轻松完成此操作。我们通过指定
breaks
来使用
cut
创建分组索引

  grp <- cut(car$carro, breaks=c(-Inf, 10, 30, Inf), right=FALSE, labels=FALSE)
grp
  car$carro <- car$carro * c(0.5, 0.9, 1.5)[grp]
  car$carro
  #[1]  1.0  1.0 10.8  9.0 21.6 45.0 75.0 82.5 90.0