kfmfe04
kfmfe04

Reputation: 15327

R: avoiding loops while inserting records into a matrix

I have a matrix m of zeros and a data-frame df containing records I want to insert into m.

# fix seed -------------------------------------------
set.seed(0)    

# create m, matrix of zeros --------------------------
rnames <- seq( 1, 100, 1 )
m <- matrix( 0, length( rnames ), length( letters ),
      dimnames=list( rnames, letters ))

# create df of random records ------------------------
r <- sample( rnames, 10, replace=TRUE )
c <- sample( letters, 10, replace=TRUE )
q <- runif( 10, -10, 10 )
df <- data.frame( r, c, q )

# want to insert df$q at r,c in m --------------------

Can I do this without resorting to a loop? What is the cleanest approach?

Upvotes: 2

Views: 215

Answers (1)

Richie Cotton
Richie Cotton

Reputation: 121127

Pass a matrix of indicies into m.

index <- cbind(
    row = df$r,
    col = match(df$c, colnames(m))       
)

m[index] <- df$q

Upvotes: 5

Related Questions