mnwepple
mnwepple

Reputation: 31

Subsetting a matrix in R

I posted a question with my original data but it was too much, so I am going to try a simpler method.

I have a matrix, [80,190]. One of my rows is Wins/Losses. I want to subset my matrix into two matrices, one with just the wins, one with just the losses.

My data looks something like this

a <- c(1, 2, 3, 4, 5)
b <- c("W", "L", "W", "W", "L")
c <- c(2, 3, 4, 5, 6)
newmat <- rbind(a, b, c)

I tried using subset

subset(newmat, newmat[2, ] == "W")

Which returns this error,

Error in x[subset & !is.na(subset), vars, drop = drop] : (subscript) logical subscript too long

Upvotes: 2

Views: 3013

Answers (2)

DatamineR
DatamineR

Reputation: 9618

Try this:

 newmat <- t(newmat)
 lapply(split(data.frame(newmat), newmat[,"b"]), t)
$L
  2   5  
a "2" "5"
b "L" "L"
c "3" "6"

$W
  1   3   4  
a "1" "3" "4"
b "W" "W" "W"
c "2" "4" "5"

Upvotes: 2

Gopala
Gopala

Reputation: 10463

You can try something like this:

winMatrix <- newmat[, which(newmat['b', ] == 'W')]
lossMatrix <- newmat[, which(newmat['b', ] == 'L')]

Upvotes: 0

Related Questions