r - 获取属于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 列中存在的唯一标签列表?
解决方案
你也可以试试
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
推荐阅读
- c++ - 使用 MPI Scatter 分布数字 - 错误
- c# - Windows8/win10 c++/c# : 有多个虚拟桌面同时处于活动状态
- angular - 对象可能是 BehaviourSubject 的“未定义”
- css - CSS - 移动设备的奇怪“放大”背景图片
- arrays - 我可以在 ruby 中有一个正则表达式数组吗?
- android - SQLite getwritableDatabase 返回 null
- java - 此生产者消费者的非法监视器状态异常?
- javascript - 如何在 C# 应用程序中显示 HTML 画布?
- angular - 在 Angular 中,如何检查相对路由是否处于活动状态?
- javascript - 使用赋值解构交换术语在函数内部不起作用