创建新变量,将数据框的所有变量除以每行中的相同变量 - R

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

我已经为只有三列的数据框完成了该操作。我想将所有变量除以 "c" 变量。

> 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

但是,如果该数据框有超过一百列怎么办,我如何设置一个循环或应用系列的东西来创建新变量?

我认为您不需要 *apply 或循环。尝试:

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

但您需要将列名设置为您想要的。

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