Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R divide each column in dataframe by last row value

Tags:

r

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.

like image 860
adam.888 Avatar asked Oct 18 '13 23:10

adam.888


2 Answers

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
like image 158
Señor O Avatar answered Nov 16 '22 00:11

Señor O


Dividing by c(df[10,]) works, as well, such as:

df1/c(df1[10,])

like image 35
aosmith Avatar answered Nov 15 '22 23:11

aosmith