CreamStat CreamStat - 4 months ago 15
R Question

Create new variables dividing all variables of a data frame by the same variable in each row - R

I've done that for a data frame with just three columns. I want to divide all variables by "c" variable.

> d <- data.frame(rep(2,7),rep(4,7),rep(8,7))
> colnames(d) <- c("a","b","c")
> #Creating the new variables
> d$c1 <- d$a/d$b
> d$c2 <- d$a/d$c
> d
a b c c1 c2
1 2 4 8 0.5 0.25
2 2 4 8 0.5 0.25
3 2 4 8 0.5 0.25
4 2 4 8 0.5 0.25
5 2 4 8 0.5 0.25
6 2 4 8 0.5 0.25
7 2 4 8 0.5 0.25


But , what if that data frame have more then one hundred columns, How Can I set a loop or something with the apply family to create the new variables?

Answer

I think you don't need *apply or a loop. Try:

cbind(d, d[, 1] / d[, -1])

But you need to set column names to your desired ones.

d <- setNames(data.frame(rep(2,7),rep(4,7),rep(8,7)), letters[1:3])
cbind(d, d[, 1] / d[, -1])
#  a b c   b    c
#1 2 4 8 0.5 0.25
#2 2 4 8 0.5 0.25
#3 2 4 8 0.5 0.25
#4 2 4 8 0.5 0.25
#5 2 4 8 0.5 0.25
#6 2 4 8 0.5 0.25
#7 2 4 8 0.5 0.25