Question

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?

Was it helpful?

Solution 2

Yes, you can use scale:

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

or sweep:

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

OTHER TIPS

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top