Xia.Song
Xia.Song

Reputation: 426

A better way to assign value for R object?

I want to randomly draw one of the obejct from (a,b,c), the probability vector is (pro_a, pro_b, pro_c) and pro_a+ pro_b+pro_c=1. The extracted object is assigned a value of 1, and the remaing are assigned a value of 0. Using the sample function and if statement, I have the following R code. How can I make the code more simple.

ev=sample(c("a","b","c"),1,c(0.2,0.3,0.5),replace=TRUE)
ev
a=0
b=0
c=0
if(ev=="a"){a=1}
if(ev=="b"){b=1}
if(ev=="c"){c=1}
a
b
c

Upvotes: 0

Views: 45

Answers (3)

user12728748
user12728748

Reputation: 8506

You could also use the old-fashioned switch statement to generate a named vector:

 switch(sample(1:3, 1, prob=c(0.2,0.3,0.5)),
        "1" = c(a=1, b=0, c=0),
        "2" = c(a=0, b=1, c=0),
        "3" = c(a=0, b=0, c=1))

Upvotes: 0

user2974951
user2974951

Reputation: 10375

Storing it into a list, which you can then put into global env

vec=c("a","b","c")
pro=c(0.2,0.3,0.5)

ran=sample(vec,1,pro,replace=T)

setNames(
  split((vec==ran)*1L,1:length(vec)),
  vec
)

$a
[1] 0

$b
[1] 1

$c
[1] 0

Upvotes: 1

Gregor Thomas
Gregor Thomas

Reputation: 145755

Use a named vector:

choices = rep(0, 3)
names(choices) = c("a", "b", "c")

ev = sample(names(choices), size = 1, prob = c(0.2, 0.3, 0.5))
# (replace = TRUE is pointless when only drawing a sample of size 1)

choices[ev] = 1
choices
# a b c 
# 0 0 1 

Upvotes: 2

Related Questions