简体   繁体   中英

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

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 

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

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM