dat <- data.frame(matrix(1:9, nrow=3))
dat / rowSums(dat)
You could also use apply
, but it will return a matrix (and require you to transpose with t
).
t(apply(dat, 1, FUN=function(x) x / sum(x)))
Domanda
I have a simple dataframe.
V1 V2 V3
1 1 4 7
2 2 5 8
3 3 6 9
I would like to divide the entries in each row by the sum of all entries in that row, and get this:
V1 V2 V3
1 0.08 0.33 0.58
2 0.13 0.33 0.53
3 0.16 0.33 0.50
It's pretty simple to use mydf[1,]/sum(mydf[1,])
and repeat it 3 times, but this is tedious.
I have an intuitive feeling that an apply function would work.
I have a vague notion I need to:
1) Put mydf[1,]/sum(mydf[1,])
in a functional wrapper
2) use apply(myfunction, 1, mydataframe)
But I'm not sure what the arguments to myfunction
would be.
I'm a little confused on this and any help is appreciated.
Soluzione
dat <- data.frame(matrix(1:9, nrow=3))
dat / rowSums(dat)
You could also use apply
, but it will return a matrix (and require you to transpose with t
).
t(apply(dat, 1, FUN=function(x) x / sum(x)))