Blight
Blight

Reputation: 87

R create vector from specific matrix elements

I'm using R to read some XML and convert it to something the deSolve library can work with. I'm trying to convert this matrix:

svars = xpathSApply(doc, "/models/model[@name='SIS']/state_variables/variable")
svars = sapply(svars, xmlAttrs)
svars

      [,1]          [,2]      
id    "S"           "I"       
name  "susceptible" "infected"
value "99"          "1" 

To a vector that looks like this:

svars = c(S = 99, I = 1)

I'm a bit at a loss on how to do this, can anyone help?

Upvotes: 0

Views: 86

Answers (2)

agstudy
agstudy

Reputation: 121608

For example:

dd <- svars[c("id","value"),]
setNames(dd$V2,dd$V3)

Or one linear :

setNames(as.numeric(svars["value", ]), svars["id",])

Upvotes: 2

CHP
CHP

Reputation: 17189

I think following should do

x <- as.numeric(svars['value', ])
names(x) <- svars['id', ]
x
##  S  I 
## 99  1

which is same as

c(S = 99, I = 1)
##  S  I 
## 99  1 

Upvotes: 1

Related Questions