Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

I am having the following data frame. I just want to know how can I normalize column X given the Pair column? 

Pair       X  

 1         2 

 1         3

 2         1

 2         2 

1 Answer

0 votes
by (108k points)

If you want to do this in base R programming, then refer to the following code:

df$norm <- with(df, X/ave(X, Pair, FUN = sum)) 

df

#  Pair X norm

#1    1 2 0.40

#2    1 3 0.60

#3    2 1 0.33

#4    2 2 0.67

The 2nd way is with dplyr package:

library(dplyr)

df %>% group_by(Pair) %>% mutate(norm = X/sum(X))

and data.table:

library(data.table)

setDT(df)[, norm := X/sum(X), Pair]

data:

df <- structure(list(Pair = c(1L, 1L, 2L, 2L), X = c(2L, 3L, 1L, 2L

)), class = "data.frame", row.names = c(NA, -4L))

Browse Categories

...