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