Skip to content

Re adout row and column of a matrix value

3 messages · Chris82, Jorge Ivan Velez, David Winsemius

#
Hello R users,

I want to readout the row and column postion from a certain matrix value
into a csv file.
I have only found this syntax 

"which(a == b, arr.ind = T)"

so I get

a = matrix

 [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    1    2    2    2    1    1    2
[2,]    1    2    3    3    3    4    4    3
[3,]    3    3    3    5    5    6    5    4
[4,]    4    4    4    3    3    4    4    3
[5,]    3    4    5    3    3    3    2    2
[6,]    3    3    3    3    3    3    2    2
[7,]    2    2    2    2    2    4    2    1
[8,]    1    1    0    0    0    0    0    0
[1] 6
row col
[1,]   3   6

but I need row and col seperate for the csv file.

row <- c("code for row")
col <- c("code for col")
value <- c("6")

#dataframe

test <- data.frame(row, col, value)

write.csv................

Thanks.

Greets
#
On Sep 17, 2008, at 3:36 PM, Jorge Ivan Velez wrote:

            
I wasn't sure that max(x) or whatever target was specified would be  
unique, and in the test case I set up    c(which(...)    did not  
maintain the matrix structure, it just appended a vector of row  
numbers to column numbers and added one max().

Perhaps consider:

x <- matrix(sample(1:10,64,replace=TRUE), nrow=8)
wmtx <- which(x==max(x), arr.ind=TRUE)  # a matrix with row and column  
numbers
wvmtx <- cbind(wmtx,val=max(x)) #argument recycling
df <- as.data.frame(wvmtx)
#if you really need to convert the value to a character then use  
as.character
df$val <- as.character(df$val)
#-------
 > str(df)
'data.frame':	8 obs. of  3 variables:
  $ row: int  1 3 5 5 7 8 4 7
  $ col: int  1 3 3 4 6 6 8 8
  $ val: chr  "10" "10" "10" "10" ...

write.csv(df, <filepath,filename> )