ywa
ywa

Reputation: 1

How to add a new column that is based on change of an existing column

I am a beginner of R and I try to use it as much as possible to advance. I want to add a new column to a existing csv file. This new column is the daily change of the 9th column. I wrote a code as follows:

for (i in nrow(period)) {
period$changeyr3<-period[i+1,9]-period[i,9]
}

changeyr3 is the name of the new column and I got all NAs.

Can you please help me?

Linda

Upvotes: 0

Views: 35

Answers (1)

Buzz Lightyear
Buzz Lightyear

Reputation: 844

You'll need to do this.

for( i in 1:nrow(period)){
   period$changeyr3[i] <- period[i+1,9] - period[i,9]
}

This should work. In what you were doing, you were setting the entire column's values to each time. Also, your last value will still be NA.

Upvotes: 1

Related Questions