Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum of independent rows of a data frame in an escalating way

Tags:

r

matrix

I have a data.frame that is 100x100 and I need to sum them up as an escalator. Starting with the first entry of the first column and then keep adding the first entry of the second column to the second entry of the first and so on until the the last entry to sum is the last row of the last column. Looking at it as a diagonal matrix such as

d3 <- data.frame(a = c(rep(0.5,5),0,0), b = c(0,rep(0.3,5),0), e = c(0,0,rep(0.8,5)))

might be helpful to understand the problem. I want to sum the rows of a matrix like d3.

I tried to create a small example but I haven't been able to create a cycle or a function that simplifies the job.

I have this data:

d <- data.frame(a = rep(0.5,5), b = rep(0.3,5), e = rep(0.8,5))

and I need a way to create a single vector with the entries:

d2 <- rep(NA)
d2[1] <- d$a[1]
d2[2] <- sum(d$a[2],d$b[1])
d2[3] <- sum(d$a[3],d$b[2],d$e[1])
d2[4] <- sum(d$a[4],d$b[3],d$e[2])
d2[5] <- sum(d$a[5],d$b[4],d$e[3])
d2[6] <- sum(d$b[5],d$e[4])
d2[7] <- d$e[5]

that is equal to c(0.5, 0.8, 1.6, 1.6, 1.6, 1.1, 0.8).

Thank you in advance for the help

like image 284
ireinstein Avatar asked Oct 19 '22 12:10

ireinstein


1 Answers

You may try

m1 <- as.matrix(d)
unname(tapply(m1, col(m1)+row(m1), FUN=sum))
#[1] 0.5 0.8 1.6 1.6 1.6 1.1 0.8
like image 91
akrun Avatar answered Oct 22 '22 23:10

akrun