[R-br] Duvida sobre if e ifelse no R

Benilton Carvalho beniltoncarvalho em gmail.com
Quinta Setembro 29 12:28:10 BRT 2011


As operações q vc executa dentro do ifelse são independentes. Por isso não
há razoes para y.values2 reter o q vc espera q ele retenha. Ele reteve a
ultima operação realizada. b

On Thursday, 29 September 2011, Augusto Ribas <ribas.aca em gmail.com> wrote:
> Ola a todos, tenho uma duvida aqui.
> Estou lendo um livro sobre programação em R e empaquei num problema aqui.
> Eu tenha a função:
>            x ≤ 0  ∈ (0, 1]    > 1
> f(x)       −x3        x2       √x
>
> ai resolvo no intervalo de -2 a 2 com o comando if:
> #começo do script
> rm(list=ls())
> # input
> x.values <- seq(-2, 2, by = 0.1)
> # for each x calculate y
> n <- length(x.values)
> y.values <- rep(0, n)
> for (i in 1:n) {
> x<-x.values[i]
> # your expression for y goes here
> if (x>1)  {
>   y<-sqrt(x)
> } else {
>   if (x<=0) {
>     y<- -x^3
>     } else {
>       y<- x^2
>   }
> }
> #end of y expression
> y.values[i] <- y
> }
> # output
> plot(x.values, y.values, type = "l")
> #até aqui tudo funcionou beleza.
> #mas dai fui tentar fazer com ifelse a mesma coisa
> y.values2 <- rep(0, n)
> resultado<-ifelse(x.values>1,y.values2<-sqrt(x.values),
>   ifelse(x.values<=0,y.values2<- -x.values^3, y.values2<- x.values^2)
> )
> #o vetor resultado fica correto
> resultado==y.values
> #mas o vetor y.values2 fica errado
> y.values2==y.values
> #o resultado ficou
>  [1] 8.000000 6.859000 5.832000 4.913000 4.096000 3.375000 2.744000
2.197000
>  [9] 1.728000 1.331000 1.000000 0.729000 0.512000 0.343000 0.216000
0.125000
> [17] 0.064000 0.027000 0.008000 0.001000 0.000000 0.010000 0.040000
0.090000
> [25] 0.160000 0.250000 0.360000 0.490000 0.640000 0.810000 1.000000
1.048809 1.303840 1.341641 1.378405
> [41] 1.414214
> #mas os valores que ficam salvos são no vetor y.values2 são:
>> y.values2
>  [1] 4.00 3.61 3.24 2.89 2.56 2.25 1.96 1.69 1.44 1.21 1.00 0.81 0.64 0.49
0.36
> [16] 0.25 0.16 0.09 0.04 0.01 0.00 0.01 0.04 0.09 0.16 0.25 0.36 0.49 0.64
0.81
> [31] 1.00 1.21 1.44 1.69 1.96 2.25 2.56 2.89 3.24 3.61 4.00
> #minha duvida então é pq ele so resolve tudo elevando ao quadrado
no y.values2
> #o que acontece, por exemplo, com o primeiro valor de resultado que vejo 8
qd mas fica salvo 4 quando vou olhar o y.values2.
> #alguém pode me iluminar sobre o que esta acontecendo?
>
>
>
>
>
> --
> Grato
> Augusto C. A. Ribas
>
> Site Pessoal: http://augustoribas.heliohost.org
> Lattes: http://lattes.cnpq.br/7355685961127056
>
>

-- 
Successful people ask better questions, and as a result, they get better
answers. (Tony Robbins)
-------------- Próxima Parte ----------
Um anexo em HTML foi limpo...
URL: <http://listas.inf.ufpr.br/pipermail/r-br/attachments/20110929/3b55e842/attachment.html>


Mais detalhes sobre a lista de discussão R-br