Reputation: 39
I'm working on R and need to select randomly a set of parameters from the following sample:
params1 <- c(a=1, b=2, c=3)
params2 <- c(a=4, b=5, c=6)
params3 <- c(a=7, b=8, c=9)
selected<-sample(c(1,2,3),size=1, replace=TRUE,
prob=c(0.33,0.33,0.33))`
However when I use the following comand,
params<-paste("params",selected,sep="")
params is a character and not the numeric set of parameters that I need.
Maybe this question is very easy, but I am used to matlab language.
Upvotes: 1
Views: 48
Reputation: 887038
We can use get
to get the value of the object.
get(paste("params",selected,sep=""))
If there are multiple objects, use mget
instead of get
and it will return a list
of values.
Or instead of sample
on 1:3, we can directly apply on the 'params'
sample(mget(ls(pattern='^params\\d+')), size=1,
prob=c(0.33,0.33,0.33))
Upvotes: 1
Reputation: 173547
The correct way to do this sort of thing in R is not to keep param1
, param2
, etc as isolated objects, but put them in a named list:
plist <- list(param1 = c(a=1, b=2, c=3),
param2 = c(a=4, b=5, c=6),
param3 = c(a=7, b=8, c=9))
And then you can select which one you want with numeric indexing, i.e. plist[[selected]]
, or by name plist[[paste0("param",selected)]]
.
Upvotes: 2