区分R中因子变量的级别

use*_*292 5 r dataset

假设我的数据集包含三列:id(标识),case(字符)和value(numeric).这是我的数据集:

tdata <- data.frame(id=c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4), case=c("a","b","c","c","a","b","c","c","a","b","c","c","a","b","c","c"), value=c(1,34,56,23,546,34,67,23,65,23,65,23,87,34,321,56))

tdata
   id case value
1   1    a     1
2   1    b    34
3   1    c    56
4   1    c    23
5   2    a   546
6   2    b    34
7   2    c    67
8   2    c    23
9   3    a    65
10  3    b    23
11  3    c    65
12  3    c    23
13  4    a    87
14  4    b    34
15  4    c   321
16  4    c    56
Run Code Online (Sandbox Code Playgroud)

如果您注意到,对于每个ID,我们有两个c.如何将它们重命名为c1和c2?(我需要区分它们以便进一步分析).

Mat*_*rde 8

怎么样:

within(tdata, case <- ave(as.character(case), id, FUN=make.unique))
Run Code Online (Sandbox Code Playgroud)

  • 我很喜欢.我想在每个`id`集合中给出他期望的内容.查看您的编辑.现在它很完美. (3认同)