pathos
March 29, 2022, 9:01pm
1
I have a small puzzle.
Given a column of a continuous variable, I would like to:
square root only the positive numbers
take out the negative numbers, make them positive, square root them, then put them back into the column
ignore the 0s and don't take the square root, for computational efficiency sake
I thought about using ifelse
, but this sounds computationally heavy. Would there be a better way?
set.seed(123)
(mydf<- data.frame(x = rnorm(10)))
#> x
#> 1 -0.56047565
#> 2 -0.23017749
#> 3 1.55870831
#> 4 0.07050839
#> 5 0.12928774
#> 6 1.71506499
#> 7 0.46091621
#> 8 -1.26506123
#> 9 -0.68685285
#> 10 -0.44566197
mydf[5, "x"] <- 0 # Set one value to zero deliberately
(mydf <- within(mydf, {y = sign(x) * sqrt(abs(x))}))
#> x y
#> 1 -0.56047565 -0.7486492
#> 2 -0.23017749 -0.4797682
#> 3 1.55870831 1.2484824
#> 4 0.07050839 0.2655342
#> 5 0.00000000 0.0000000
#> 6 1.71506499 1.3096049
#> 7 0.46091621 0.6789081
#> 8 -1.26506123 -1.1247494
#> 9 -0.68685285 -0.8287659
#> 10 -0.44566197 -0.6675792
Created on 2022-03-29 by the reprex package (v2.0.1)
1 Like
pathos
March 30, 2022, 1:00pm
3
Ah sorry, I should have clarified from the beginning for a dplyr
or tidytable
equivalent
(mydf <- mydf%>% mutate( y = sign(x) * sqrt(abs(x))))
Note : This might be simplified by removing sign(x) *
, as when you list out what to do with them (2) you dont say to make them negative as a subsequent step.
Also, the solution doesnt skip 0's but I don't see a motivated reason to skip them either.
2 Likes
system
Closed
April 20, 2022, 1:38pm
5
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed. If you have a query related to it or one of the replies, start a new topic and refer back with a link.