Hi Philip,

Why do you want to use ifelse? It is not an alternative to an if then else structure, but a way of iterating over a vector with a statement, returning one value it is true, another if false. An example:

x = runif(100)
y = ifelse(x > 0.5, "Larger", "Smaller")
x
y

cheers,
Paul

On 08/18/2010 11:18 AM, Philip Wong wrote:
hello people,
I want to make a biased dice using the sample() function and print out the
results after n number of runs, I've successfully generated the dice using
the following command:
mydie2<-function(n=1000,y=NULL,...){
for(i in 1:n){
x<-sample(1:6,n,replace=TRUE,prob=c(1,1,2,3,2,1)/10)
x=runif(n)
if(x<=1/10){y[i]=1}
else if(x<=2/10){y[i]=2}
else if(x<=4/10){y[i]=3}
else if(x<=7/10){y[i]=4}
else if(x<=9/10){y[i]=5}
else{y[i]=6}
}
bar<-barplot(table(y))
table<-table(y)
return(list(bar,table))
}

mydie2()


but I also want to try to create the same dice stimulation using ifelse()
statement, but all hell break loose when I attempt to use the command below
(the barplot only shows the results to be 6), can anyone tell me what went
wrong please:
mydie2<-function(n=1000,y=NULL,...){
for(i in 1:n){
x<-sample(1:6,n,replace=TRUE,prob=c(1,1,2,3,2,1)/10)
x=runif(n)
ifelse((x<=1/10),{y[i]<-1},
ifelse((x<=2/10),{y[i]<-2},
ifelse((x<=4/10),{y[i]<-3},
ifelse((x<=7/10),{y[i]<-4},
ifelse((x<=9/10),{y[i]<-5},{y[i]<-6})))))

}
bar<-barplot(table(y))
table<-table(y)
return(list(bar,table))
}


mydie2()


--
Drs. Paul Hiemstra
Department of Physical Geography
Faculty of Geosciences
University of Utrecht
Heidelberglaan 2
P.O. Box 80.115
3508 TC Utrecht
Phone:  +3130 253 5773
http://intamap.geo.uu.nl/~paul
http://nl.linkedin.com/pub/paul-hiemstra/20/30b/770

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to