J.Doe
J.Doe

Reputation: 139

Manipulate data frame columns

I have a data frame in the format of:

Col A   ColB   ColC  
"Text1" 30     50
"Text2" 100    120
"Text3" 500    560
"Text4" 705    800

And so on...

I want to achieve a data frame that looks like:

Col A   ColB   ColC  ColD
"Text1" 30     50    99
"Text2" 100    120   499
"Text3" 500    560   704
"Text4" 705    800   ...(Text5's position -1)

I basically want to get the following texts "ColB-1" inserted into the previous text's ColD. I was wondering how I could do so?

Upvotes: 1

Views: 42

Answers (3)

Saman
Saman

Reputation: 523

You can use the vector of your variable and for the last one for example use 0 :

df[,4]=c(df[2:nrow(df),2]-1,0)

Upvotes: 0

stevec
stevec

Reputation: 52208

Here's a simple way (using iris as an example)

library(dplyr)

iris$newcol <- lead(iris$Petal.Width - 1, n=1)
head(iris)

Upvotes: 1

YOLO
YOLO

Reputation: 21709

You can do the following:

library(data.table)
setDT(df)
df[, ColD := shift(ColB, n = 1, type = 'lead', fill = 0)-1]

    ColA ColB ColC ColD
1: Text1   30   50   99
2: Text2  100  120  499
3: Text3  500  560  704
4: Text4  705  800   -1

Upvotes: 2

Related Questions