R 基于两列中的组唯一id创建序列号
我有这些数据R 基于两列中的组唯一id创建序列号,r,serialization,dplyr,group-by,mutate,R,Serialization,Dplyr,Group By,Mutate,我有这些数据 cluster<-c(1,1,1,1,2,2,2,2) structure<-c(1,1,2,3,1,1,1,2) str<-data.frame(clusters,structures) cluster如果您使用的是base R,请尝试ave+seq\u within(str, serial.number <- ave(structure,cluster,FUN = seq_along)) 内(str,serial.number我想你在找这个: lib
cluster<-c(1,1,1,1,2,2,2,2)
structure<-c(1,1,2,3,1,1,1,2)
str<-data.frame(clusters,structures)
cluster如果您使用的是base R,请尝试ave
+seq\u
within(str, serial.number <- ave(structure,cluster,FUN = seq_along))
内(str,serial.number我想你在找这个:
library(data.table)
df <- setDT(str)
df[, serial.number := seq(.N), by = .(cluster,structure)]
库(data.table)
df使用dplyr
library(dplyr)
df %>%
group_by(cluster, structure) %>%
mutate(serial.number = row_number())
或使用数据。表格
library(data.table)
setDT(df)[, serial.number := rowid(cluster, structure)]
str$serial.numberworks运行得很好,但是有没有其他选择,而不使用data.table?可能有其他选择,但我故意使用datatable。您不想使用datatable的原因是什么?
library(data.table)
setDT(df)[, serial.number := rowid(cluster, structure)]