Home > Mobile >  The if else statement compare to 0
The if else statement compare to 0

Time:11-17

I try to get the square root of negative number. I got the absolute value of data and, for the positive number, I use the squart root of absolute number directly, otherwive add an negaitve sign to the result. However all numbers I got are negaitve...

My code Results shown

I try to get negaitve and positive results, but I only got negative numbers.your text``your text

CodePudding user response:

Library and Data

Not sure exactly what you are doing because your original data frame isn't included in the question. However, I have simulated a dataset that should emulate what you want depending on what you are doing. First, I loaded the tidyverse package for data wrangling like creating/manipulating variables, then set a random seed so you can reproduce the simulated data.

#### Load Library ####
library(tidyverse)

#### Set Random Seed ####
set.seed(123)

Now I create a randomly distributed x value that is both positive and negative.

#### Create Randomly Distributed X w/Neg Values ####
tib <- tibble(
  x = rnorm(n=100)
)

Creating Variables

Now we can make absolute values, followed by square roots, which are made negative if the original raw value was negative.

#### Create Absolute and Sqrt Values ####
new.tib <- tib %>% 
  mutate(
    abs.x = abs(x),
    sq.x = sqrt(abs.x),
    final.x = ifelse(x < 0,
                     sq.x * -1,
                     sq.x)
    )
new.tib

If you print new.tib, the end result will look like this:

 # A tibble: 100 × 4
         x  abs.x  sq.x final.x
     <dbl>  <dbl> <dbl>   <dbl>
 1  2.20   2.20   1.48    1.48 
 2  1.31   1.31   1.15    1.15 
 3 -0.265  0.265  0.515  -0.515
 4  0.543  0.543  0.737   0.737
 5 -0.414  0.414  0.644  -0.644
 6 -0.476  0.476  0.690  -0.690
 7 -0.789  0.789  0.888  -0.888
 8 -0.595  0.595  0.771  -0.771
 9  1.65   1.65   1.28    1.28 
10 -0.0540 0.0540 0.232  -0.232

If you just want to select the final x values, you can simply select them, like so:

new.tib %>% 
  select(final.x)

Giving you just this vector:

# A tibble: 100 × 1
   final.x
     <dbl>
 1   1.48 
 2   1.15 
 3  -0.515
 4   0.737
 5  -0.644
 6  -0.690
 7  -0.888
 8  -0.771
 9   1.28 
10  -0.232
# … with 90 more rows

CodePudding user response:

Using the first example in ?ifelse:

x <- c(6:-4)
[1] 6 5 4 3 2 1 0 -1 -2 -3 -4
sqrt(ifelse(x >= 0, x, -x))
[1] 2.449490 2.236068 2.000000 1.732051 1.414214 1.000000
[7] 0.000000 1.000000 1.414214 1.732051 2.000000
  •  Tags:  
  • r
  • Related