尝试
raw$slot <- with(raw, paste0("slot",as.numeric(factor(id))))
raw
# id Cap Rs R_inv slot
#257 464A485SSEE3 1.41e-10 736665.1 1.36e-06 slot1
#258 464A485SSEE3 1.30e-10 364822.7 2.74e-06 slot1
#289 464A485TSEB2 1.44e-10 111996.1 8.93e-06 slot2
#290 464A485TSEB2 1.33e-10 108541.0 9.21e-06 slot2
或者,如果数据集按 排序id
,您也可以这样做
raw$slot <- paste0("slot",cumsum(c(TRUE,raw$id[-1]!=raw$id[-nrow(raw)])))
更新
如果您需要一些自定义标签,您可以将其转换id
为factor
(如果不是)并指定labels
您想要的
raw$slot <- with(raw, as.character(factor(id, labels=c('split6', 'split9'))) )
raw$slot
#[1] "split6" "split6" "split9" "split9"
或者只是numeric
通过转换factor
来使用索引并在该索引上numeric
使用向量。names
在这里,您需要在执行此操作之前知道级别的顺序。
with(raw, c('split6', 'split9')[as.numeric(factor(id))])
#[1] "split6" "split6" "split9" "split9"
数据
raw <- structure(list(id = c("464A485SSEE3", "464A485SSEE3", "464A485TSEB2",
"464A485TSEB2"), Cap = c(1.41e-10, 1.3e-10, 1.44e-10, 1.33e-10
), Rs = c(736665.125, 364822.6875, 111996.1016, 108541), R_inv = c(1.36e-06,
2.74e-06, 8.93e-06, 9.21e-06)), .Names = c("id", "Cap", "Rs",
"R_inv"), class = "data.frame", row.names = c("257", "258", "289", "290"))