3

I would like to create a new column inside my data table, this column being a vector of values; but I am getting the following error:

DT = data.table(x=rep(c("a","b"),c(2,3)),y=1:5)
> 
> DT
   x y
1: a 1
2: a 2
3: b 3
4: b 4
5: b 5
> DT[, my_vec := rep(0,y)]
Error in rep(0, y) : invalid 'times' argument

My expected result is:

> DT
   x y my_vec
1: a 1 0
2: a 2 0 0
3: b 3 0 0 0
4: b 4 0 0 0 0
5: b 5 0 0 0 0 0

Is there a way to do that?

2 Answers 2

7

The syntax is a little cumbersome, but you can do this:

DT[, my_vec := list(list(rep(0, y))), by = y]
DT
#   x y    my_vec
#1: a 1         0
#2: a 2       0,0
#3: b 3     0,0,0
#4: b 4   0,0,0,0
#5: b 5 0,0,0,0,0
Sign up to request clarification or add additional context in comments.

Comments

5

It is not clear whether you need a list as my_vec or a vector. If it is the latter, we group by sequence of rows, replicate the 0 with 'y' and paste the elements together within each group.

DT[, my_vec := paste(rep(0, y), collapse=' ') , 1:nrow(DT)]
DT
#   x y    my_vec
#1: a 1         0
#2: a 2       0 0
#3: b 3     0 0 0
#4: b 4   0 0 0 0
#5: b 5 0 0 0 0 0

Comments

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.