Dividing each element from a dataframe by specific elements of a second dataframe

StackOverflow https://stackoverflow.com/questions/23415145

  •  13-07-2023
  •  | 
  •  

I have two data frames:

x = data.frame(replicate(10,sample(1:6,1000,rep=TRUE)))
y = t(data.frame(apply(x, 2, sum)))

How do I divide each element form x per column by the element in y in the column with the same name. Also, what would be a better way to write y?

I have tried a nested apply:

apply(y, 2, function(y){
    sapply(x, function(x) (x/y))
})

Is there a better way?

有帮助吗?

解决方案 2

Yes, you can use scale:

scale(x, center=FALSE, scale=y)

or sweep:

sweep(x, 2, y, FUN='/')

其他提示

A better way to write y will be

y <- colSums(x)

And in order to "divide each element form x per column by the element in y" you can try

mapply("/", x, y)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top