我的问题并不复杂,但我在网上没有找到答案。简而言之,我想知道如何创建一个新列并向其添加 seq() 。问题是我不知道需要的重复次数。我知道您可以指定 rep
参数,但是如果您事先不知道数据是什么怎么办?有没有办法用 data.table
做到这一点? :
data <- data[, new.col := seq(1,3,1)]
从逻辑上讲,这会返回以下错误:
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.
这是我当前拥有的数据和我想要的输出的示例:
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
我知道它会起作用,但我不想指定 seq()
所需的 rep
数量。
谢谢。
最佳答案
您可以使用 rep
的 length.out
参数
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
您还可以使用rep_len
df[, new.col := rep_len(1:3, .N)]
关于r - 如何在不知道重复次数的情况下创建由序列组成的新列 - 数据表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57995407/