Gainz
Gainz

Reputation: 1771

How to create a new column made of a sequence without knowning the number of repetitions - data.table

my question is far from being a complex one but I didn't find the answer online. To put it simple, I would like to know how to create a new column and add a seq() to it. The problem is that I don't know the number of repetitions that will be need. I know you can specify the rep argument but what if you don't know what is the data in advance? Is there a way to do this with data.table ? :

data <- data[, new.col := seq(1,3,1)]

This is logically returning me the following error:

Error in [.data.table(data, , :=(new.col, seq(1, 3, 1))) :
Supplied 3 items to be assigned to 13502 items of column 'new.col'. The RHS length must either be 1 (single values are ok) or match the LHS length exactly. If you wish to 'recycle' the RHS please use rep() explicitly to make this intent clear to readers of your code.

Here is an example of the data I currently have and the output I want:

current data

id  sexe
109   F
100   F 
157   M 
151   M 
160   M 
168   M



desired output

id  sexe new.col
109   F     1
100   F     2
157   M     3
151   M     1
160   M     2
168   M     3

I know it would work but I don't want to specify the the number of rep needs for the seq().

Thank you.

Upvotes: 4

Views: 1467

Answers (2)

akrun
akrun

Reputation: 887991

We can use base R

df$new.col <- rep(1:3, length.out = nrow(df))

Upvotes: 1

IceCreamToucan
IceCreamToucan

Reputation: 28705

You can use the length.out argument of rep

df[, new.col := rep(1:3, length.out = .N)]

df
#     id sexe new.col
# 1: 109    F       1
# 2: 100    F       2
# 3: 157    M       3
# 4: 151    M       1
# 5: 160    M       2
# 6: 168    M       3

You can also use rep_len

df[, new.col := rep_len(1:3, .N)]

Upvotes: 4

Related Questions