r - Adding to a numeric matrix with data from a dataframe -
i'm wondering if missing faster way of doing following, other doing laborious loop.
say have matrix this:
m1 <- structure(c(0, 2, 2, 1, 0, 1, 1, 1, 0), .dim = c(3l, 3l), .dimnames = list( c("ak", "jw", "sz"), c("ak", "jw", "sz"))) #m1 # ak jw sz # ak 0 1 1 # jw 2 0 1 # sz 2 1 0
now, want add values following dataframe. here can see individuals listed in 'id1' , 'id2' , value add in 'val'.
dfx <- structure(list(id1 = c("jw", "sz", "sz"), id2 = c("ak", "ak", "jw"), val = c(1.5, 2.5, 1)), .names = c("id1", "id2", "val"), row.names = c(na, -3l), class = "data.frame") #dfx # id1 id2 val #1 jw ak 1.5 #2 sz ak 2.5 #3 sz jw 1.0
each value should added respective cell of matrix e.g 2.5 should added m1[sz, ak]
. however, same value should added transposed cell, i.e. 2.5 should added m1[ak, sz]
.
the resulting matrix should like:
# ak jw sz #ak 0.0 2.5 3.5 #jw 3.5 0.0 2.0 #sz 4.5 2.0 0.0
this can achieved instance creating loop every row of 'dfx':
m1[rownames(m1)=="jw",rownames(m1)=="ak"] <- m1[rownames(m1)=="jw",rownames(m1)=="ak"] + 1.5 m1[rownames(m1)=="ak",rownames(m1)=="jw"] <- m1[rownames(m1)=="ak",rownames(m1)=="jw"] + 1.5
any ideas/pointers better way appreciated:
a possible base
alternative data frame reshaped same dimensions matrix. achieved first converting 'id1' , 'id2' factor
s levels
picked 'm1'. xtabs
used reshaping. result , t
ranspose added 'm1'.
dfx[ , c("id1", "id2")] <- lapply(dfx[ , c("id1", "id2")], function(x) factor(x, levels = rownames(m1))) m2 <- xtabs(val ~ ., data = dfx) m1 + m2 + t(m2) # ak jw sz # ak 0.0 2.5 3.5 # jw 3.5 0.0 2.0 # sz 4.5 2.0 0.0
Comments
Post a Comment