Ushuaia81
Ushuaia81

Reputation: 564

Adding columns dynamically on data table depending on a column value

What is the best way to add a sequence column in a data.table depending on a fixed selected value and a value defined by a column. The following example ilustrates the input and desired output:

library(data.table)

# Input
# Add a column sequence till 7 starting from the value of column V2. 
dt <- data.table(c("A","D","H"), c(2, 4, 5))

# Desired Ouput
dt <- data.table(c(rep("A", 6), rep("D", 4), rep("H", 3)), new_column = c(2:7, 4:7, 5:7))
dt 

Upvotes: 0

Views: 216

Answers (1)

rosscova
rosscova

Reputation: 5580

Does this achieve what you're after?

dt[ , .( new_column = V2:7 ), by = V1 ]

output:

    V1 new_column
 1:  A          2
 2:  A          3
 3:  A          4
 4:  A          5
 5:  A          6
 6:  A          7
 7:  D          4
 8:  D          5
 9:  D          6
10:  D          7
11:  H          5
12:  H          6
13:  H          7

Upvotes: 4

Related Questions