我需要一些帮助。
我有一个包含多列的表格。一个从1到30变化,另一个从1到6变化。其他列有多个值。我需要的是存储第1列的值1和第2列的1的索引,第1列的值为1,第2列的值为2,因此第1列的第4 ...值2,值2为第二列,所以第四列,直到我拥有所有索引。
提前谢谢
答案 0 :(得分:0)
您可以使用'which'函数来获取索引:
y = sample(1:6, 30, replace=T)
x = sample(1:30, 30, replace=T)
df = data.frame(x,y)
head(df)
x y
1 22 1
2 13 5
3 28 4
4 28 3
5 7 3
6 30 6
which(df$x==2)
[1] 16 22
which(df$y==2)
[1] 10 11 12 18 21 27
您可以使用简单的'for'循环进行多项测试:
for(i in 1:6){
cat("indexes of",i,"in x:\n")
print(which(df$x==i))
cat("indexes of",i,"in y:\n")
print(which(df$y==i))
cat("\n")
}
indexes of 1 in x:
integer(0)
indexes of 1 in y:
[1] 1 9 14 19 24 26
indexes of 2 in x:
[1] 16 22
indexes of 2 in y:
[1] 10 11 12 18 21 27
indexes of 3 in x:
integer(0)
indexes of 3 in y:
[1] 4 5 17
indexes of 4 in x:
integer(0)
indexes of 4 in y:
[1] 3 7 13 20 23 28
indexes of 5 in x:
[1] 23
indexes of 5 in y:
[1] 2 15 16 29 30
indexes of 6 in x:
integer(0)
indexes of 6 in y:
[1] 6 8 22 25
对于所有列:
for(i in 1:6) {for(j in 1:ncol(df)) {cat("indexes of",i,"in",names(df)[j],'\n'); print(which(df[[j]]==i))} ;cat('\n')}
indexes of 1 in x
integer(0)
indexes of 1 in y
[1] 1 9 14 19 24 26
...