# R how to do the calculation in different lines of the data.frame

## Question:

I'm doing it as follows:

temp <- data.frame(ano = c(1997,1999,2001,2003,2005,2007,2009,2013,2019))

a <- (temp[2,1]-temp[1,1])+1

b <- (temp[3,1]-temp[1,1])+1

c <- (temp[4,1]-temp[1,1])+1

d <- (temp[5,1]-temp[1,1])+1

f <- (temp[6,1]-temp[1,1])+1

g <- (temp[7,1]-temp[1,1])+1

h <- (temp[8,1]-temp[1,1])+1

i <- (temp[9,1]-temp[1,1])+1

temp["t"] <- c(1,a,b,c,d,f,g,h,i)

I arrive at the following result:

ano   t
1997  1
1999  3
2001  5
2003  7
2005  9
2007  11
2009  13
2013  17
2019  23

How do I optimize this process, without having to always declare the variables? Is there any way to do these calculations directly in the data.frame in a way that the first line is always t=1 and the others following the formula in column t of the data.frame :

linha2=(ano2-ano1)+1
linha3=(ano3-ano1)+1

and so on.

How can this process be automatic? No t column variable declarations, just declaring the years of the first column, so it can be used in other entries in the ano column.

R is a language that allows you to do vector calculations, so just:

temp\$t <- (temp\$ano - 1997) +1

so that the account is applied to all rows in your data.frame .

Scroll to Top