![](/img/trans.png)
[英]R - Create a new variable where each observation depends on another table and other variables in the data frame
[英]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
或loop。 嘗試:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.