kcm
kcm

Reputation: 200

How can I loop through a data frame and if I find the desired value then print the column and row name or indices?

m = matrix(runif(100), ncol=10)
rownames(m) = LETTERS[1:10]
colnames(m) = rownames(m)
m

I get a matrix ,so I want to loop through each rows and column , I want to compare the first element in my row to all the element thats present in the column

   A          B         C         D          E          F         G `                                                                    
A 0.2059746 0.93470523 0.4820801 0.8209463 0.47761962 0.91287592 0.3390729 
B 0.1765568 0.21214252 0.5995658 0.6470602 0.86120948 0.29360337 0.8394404 

So i want to compare 1st row that is A to A,B,C,D,E,F,F check the desired value if it exist then print the index or rows and column name ..

which(m >0.8, arr.ind=TRUE)

I did this but I want to do it using for loop

Any help or suggestion would be highly appreciated

Upvotes: 1

Views: 1702

Answers (1)

Roman Luštrik
Roman Luštrik

Reputation: 70633

How's this?

for (i in 1:nrow(m)) {
  findrows <- which(m[i, ] > 0.8)
  if (length(findrows) > 0) {
    print(rownames(m[i, , drop = FALSE]))
  }
}

To also print columns, just add an extra line:

for (i in 1:nrow(m)) {
  findrows <- which(m[i, ] > 0.8)
  if (length(findrows) > 0) {
    message("rows:")
    print(rownames(m[i, , drop = FALSE]))
    message("columns:")
    print(colnames(m[, findrows, drop = FALSE]))
  }
}

Upvotes: 3

Related Questions