I have a dataframe and am trying to divide each column in dataframe by last row value:
A <- c(1:10)
B <- c(2:11)
C <- c(3:12)
df1 <- data.frame(A,B,C)
df2 <- df1/df1[10,]
However I get an error. I would be grateful to know what I am doing wrong.
data.frames
aren't made for those kinds of operations.
data.frame(lapply(df1, function(X) X/X[10]))
Should do the trick. Or use a matrix instead.
df1 = as.matrix(df1)
> t(t(df1)/df1[10,])
A B C
[1,] 0.1 0.1818182 0.2500000
[2,] 0.2 0.2727273 0.3333333
[3,] 0.3 0.3636364 0.4166667
[4,] 0.4 0.4545455 0.5000000
[5,] 0.5 0.5454545 0.5833333
[6,] 0.6 0.6363636 0.6666667
[7,] 0.7 0.7272727 0.7500000
[8,] 0.8 0.8181818 0.8333333
[9,] 0.9 0.9090909 0.9166667
[10,] 1.0 1.0000000 1.0000000
Dividing by c(df[10,])
works, as well, such as:
df1/c(df1[10,])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With