praks5432
praks5432

Reputation: 7792

How to increment column in R data frame by one?

So I have data like this

            Date    DJIA Time
1     1/1/96 5117.12    1
2     1/2/96 5177.45    2
3     1/3/96 5194.07    3
4     1/4/96 5173.84    4
5     1/5/96 5181.43    5
6     1/8/96 5197.68    6

I want to decrement the values in the Time column by 1 and remove the first row.

I've achieved both of these steps separately-

data[-1,]

removes the first row, while

data$Time - 1 

decrements, but returns me the decremented columns.

How do I make it so that I get something like this

        Date    DJIA Time
1     1/2/96 5177.45    1
2     1/3/96 5194.07    2
3     1/4/96 5173.84    3
4     1/5/96 5181.43    4
5     1/8/96 5197.68    5

?

I've also tried

data[-1,]$Time - 1 

but this again returns me only the time vector decremented by 1, as opposed to changing the entire data frame.

Upvotes: 0

Views: 5813

Answers (1)

Julián Urbano
Julián Urbano

Reputation: 8488

This you got right:

data[-1,]
data$Time - 1

But, as you said, it returns a new data frame; it doesn't change what you already have. So you just need to assign the result back to data:

data <- data[-1,]
data$Time <- data$Time - 1

To better understand, you can do newData <- data[-1,] to create a new data frame without the first row. If you want to transform your original data frame, you need to re-assign it data <- .... Same goes for columns or rows, you need to do data$column <- ....

Upvotes: 4

Related Questions