Philip John
Philip John

Reputation: 5565

R scale one value based on other

Is there a way to scale one value to a fixed value and the other value to the corresponding scaled value. I was not able to use scale method in R as it needs a range.

For eg,

ID    X    Y
1     25   25   
2     20   40
3     10   50
4     50   20

I need to scale the Y value to a fixed value of 100. Correspondingly X value should be scaled accordingly.

ID    X    Y
1     100   100   
2     50    100
3     20    100
4     250   100

Upvotes: 1

Views: 310

Answers (2)

Konrad
Konrad

Reputation: 18585

Presumably you may also consider having a quick look at the scalefunction available in the base package. For instance, if you wish to scale part of the data frame, you could:

data("mtcars")
test <- scale(x = mtcars[,2:ncol(mtcars)], scale = TRUE)

You could easily modify the syntax further setting the base and centre so the obtained scales matches your requirements:

tst_mpg <- scale(x = mtcars$mpg, scale = 1, center = 0.5)

Upvotes: 0

rmuc8
rmuc8

Reputation: 2989

If your data is

id <- c(1,2,3,4)
X <- c(25,20,10,50)
Y <- c(25,40,50,20)
df <- data.frame(id,X,Y)

you could try

df$X <- df$X*100/df$Y
df$Y <- 100


# > df
#   id   X   Y
# 1  1 100 100
# 2  2  50 100
# 3  3  20 100
# 4  4 250 100

Upvotes: 3

Related Questions