0

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 

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect @rosscova.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.