我有一个看起来像这样的数据框:
id = c("A","B","C","A","C","C")
val = c(5,4,6,7,10,99)
df = data.frame(id, val)
df
id val
A 5
B 4
C 6
A 7
C 10
C 99
现在我想重新排列id
列(A,B,C...),保留它们对应val
的 ,然后添加一个newid
以字母 E 开头的新列,后跟三个数字,计算id
第一列中的个数。代码在这里:
id2 = c("A","A","B","C","C","C")
val2 = c(5,7,4,6,10,99)
newid = c("E001","E002","E001","E001","E002","E003")
df2 = data.frame(id2, val2, newid)
df2
最终结果是这样的:
id2 val2 newid
A 5 E001
A 7 E002
B 4 E001
C 6 E001
C 10 E002
C 99 E003
有没有一种有效的方法来做到这一点?