我有以下数据框,
>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列中存在的唯一标签列表?
答案 0 :(得分:1)
我们可以使用split
根据唯一的Label
获取索引列表
split(1:nrow(df), df$Label)
#$control1
#[1] 1 2 5
#$control2
#[1] 3 4
使用df2
split(1:nrow(df2), df2$Label)
#$trol1
#[1] 1 2
#$trol2
#[1] 3 5
#$trol3
#[1] 4
答案 1 :(得分:1)
使用var request = require('request');
request({
url: 'https://api.<api_name>.com/stations',
headers: {
'Accept': application/json,
'Authorization: Bearer': <my_key>
}
和unique
,您可以执行以下操作:
which
答案 2 :(得分:1)
您也可以尝试
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