首页 > 解决方案 > 获取属于R中公共组的元素的索引

问题描述

我有以下数据框,

>df
  Label
0 control1
1 control1
2 control2
3 control2
4 control1

要获取带有标签 control1 和 control2 的元素的索引,我执行以下操作

Index1 <- grep("control1",df[,1])
Index2 <- grep("control2",df[,1])

在上述语法中,命令中明确提到了标签 control1 和 control2。

有没有办法自动找到标签?原因是数据框df,内容是从不同的输入文件中解析出来的。例如,我可以有另一个读取的数据框

>df2
  Label
0 trol1
1 trol1
2 trol2
3 trol3
4 trol2

有没有办法创建 df 列中存在的唯一标签列表?

标签: rgrouping

解决方案


你也可以试试

lapply(unique(df$Label), function(x) which(df$Label%in% x))

#with df
[[1]]
[1] 1 2 5

[[2]]
[1] 3 4

lapply(unique(df2$Label), function(x) which(df2$Label%in% x))
#with df2
[[1]]
[1] 1 2

[[2]]
[1] 3 5

[[3]]
[1] 4

推荐阅读