[R] Re adout row and column of a matrix value
David Winsemius
dwinsemius at comcast.net
Wed Sep 17 22:15:53 CEST 2008
On Sep 17, 2008, at 3:36 PM, Jorge Ivan Velez wrote:
> Hi Chris82,
>
> Try this:
>
> res=c(which(a == max(a), arr.ind = T),max(a))
> names(res)=c('row','col','value')
> write.csv(res,"C://yourfile.csv",row.names=TRUE)
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> )
--
David Winsemius
>
>
> On Wed, Sep 17, 2008 at 1:47 PM, Chris82 <rubenbauar at gmx.de> wrote:
>
>>
>> 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
>>
>>> print(max(a))
>> [1] 6
>>> which(a == max(a), arr.ind = T)
>> 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
>>
>> --
>> View this message in context:
>> http://www.nabble.com/Readout-row-and-column-of-a-matrix-value-tp19537540p19537540.html
>> Sent from the R help mailing list archive at Nabble.com.
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list