对数据 使用ave,或: ddply_dplyr``data.table df$num 或者: library(plyr)ddply(df, .(cat), mutate, id = seq_along(val)) 或者: library(dplyr)df %>% group_by(cat) %>% mutate(id = row_number()) 或(最有效的内存,因为它通过
使用ave,或: ddply_dplyr``data.table
df$num <- ave(df$val, df$cat, FUN = seq_along)
或者:
library(plyr)ddply(df, .(cat), mutate, id = seq_along(val))
或者:
library(dplyr)df %>% group_by(cat) %>% mutate(id = row_number())
或(最有效的内存,因为它通过引用分配DT):
library(data.table)DT <- data.table(df)DT[, id := seq_len(.N), by = cat]DT[, id := rowid(cat)]