4 回答
TA贡献1813条经验 获得超2个赞
因为我做了这个r-常见问题更完整的问题,一个基本的R选项sequence和rle:
df$num <- sequence(rle(df$cat)$lengths)
它给出了预期的结果:
> df
cat val num
4 aaa 0.05638315 1
2 aaa 0.25767250 2
1 aaa 0.30776611 3
5 aaa 0.46854928 4
3 aaa 0.55232243 5
10 bbb 0.17026205 1
8 bbb 0.37032054 2
6 bbb 0.48377074 3
9 bbb 0.54655860 4
7 bbb 0.81240262 5
13 ccc 0.28035384 1
14 ccc 0.39848790 2
11 ccc 0.62499648 3
15 ccc 0.76255108 4
12 ccc 0.88216552 5
如果df$cat是一个因素变量,您需要将它包装在as.character第一:
df$num <- sequence(rle(as.character(df$cat))$lengths)
TA贡献1851条经验 获得超4个赞
for
for (i in unique(df$cat)) df$num[df$cat == i] <- seq_len(sum(df$cat == i))
TA贡献1859条经验 获得超6个赞
我想添加一个data.table变量使用rank()函数,它提供了更改顺序的额外可能性,从而使其比seq_len()解决方案,非常类似于RDBMS中的行号函数。
# Variant with ascending ordering
library(data.table)
dt <- data.table(df)
dt[, .( val
, num = rank(val))
, by = list(cat)][order(cat, num),]
cat val num
1: aaa 0.05638315 1
2: aaa 0.25767250 2
3: aaa 0.30776611 3
4: aaa 0.46854928 4
5: aaa 0.55232243 5
6: bbb 0.17026205 1
7: bbb 0.37032054 2
8: bbb 0.48377074 3
9: bbb 0.54655860 4
10: bbb 0.81240262 5
11: ccc 0.28035384 1
12: ccc 0.39848790 2
13: ccc 0.62499648 3
14: ccc 0.76255108 4
# Variant with descending ordering
dt[, .( val
, num = rank(-val))
, by = list(cat)][order(cat, num),]
- 4 回答
- 0 关注
- 844 浏览
添加回答
举报