R how to calculate on different lines of the date.

Asked

Viewed 204 times

5

I’m doing it this way:

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 come to 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 always having to declare the variables? Is there any way to do these calculations directly on data.frame in a way that the first line is always t=1 and the others following the formula in the column t of data.frame:

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

and so on.

Can this process be automatic? No column variable statements t, declaring only the years of the first column so that it can be used in other entries in the column ano.

1 answer

4


The 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 of your data.frame.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.