indexing - store indexes from a table in R -
i need in here.
i have table multiple columns. 1 varying 1 30 , 1 6. other columns have multiple values. need store indexes value 1 1st column , 1 2nd column, value 1 first column , 2 2nd column , fourth... value 2 1st column, value 2 2nd column , fourth till have indexes.
thank in advance
you can use 'which' function indexes:
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 you can use simple 'for' loop multiple tests:
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 columns:
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 ...
Comments
Post a Comment