[R] Replace NAs in a data frame with elements randomly generated from the beta distribution
arun
smartpink111 at yahoo.com
Wed Apr 10 22:39:48 CEST 2013
Hi,
Try this:
which(MAT==0)
#[1] 10 19 22 27 28 34 40 46 51 52
MAT[MAT==0]<-sapply(seq_along(MAT[MAT==0]),function(x)rbeta(1,0.1,1))
MAT
# X1 X2 X3 X4 X5 X6
#1 0.68 9.731207e-14 0.03005021 0.003249449 1.360000e+00 1.180602e-03
#2 9.86 1.150000e+01 1.79000000 7.950000000 1.610000e+00 6.030000e+00
#3 1.29 3.267000e+01 5.89000000 3.820000000 2.020000e+00 1.300000e+00
#4 0.25 9.800000e-01 0.01599430 0.640000000 1.896959e-08 1.740000e+00
#5 5.28 3.060000e+00 10.36000000 0.930000000 1.036000e+01 7.070000e+00
#6 1.13 2.970000e+00 1.20000000 0.730000000 1.510000e+00 1.758980e-06
#7 1.66 5.100000e-01 2.06000000 0.004797795 1.040000e+00 1.660495e-14
#8 0.41 1.362000e+01 0.16000000 5.430000000 1.930000e+00 9.200000e+00
#9 2.65 1.230000e+00 0.04859186 1.450000000 1.400000e+00 1.900000e-01
A.K.
----- Original Message -----
From: Sibusiso Ndzukuma <sibusisondzukuma at webmail.co.za>
To: r-help at r-project.org
Cc:
Sent: Wednesday, April 10, 2013 7:09 AM
Subject: [R] Replace NAs in a data frame with elements randomly generated from the beta distribution
Hi there!
Please help me, I am trying to replace all NAs in a data frame with numbers
randomly generated from the beta(0.1,1) distribution. Firstly I tried looping:
MAT <-
c(0.68,9.86,1.29,0.25,5.28,1.13,1.66,0.41,2.65,0.00,11.5,32.67,0.98,3.06,2.97,0.51,13.62,1.23,0.00,1.79,5.89,0.00,10.36,1.20,2.06,0.16,0.00,0.00,7.95,3.82,0.64,0.93,0.73,0.00,5.43,1.45,1.36,1.61,2.02,0.00,10.36,1.51,1.04,1.93,1.40,0.00,6.03,1.30,1.74,7.07,0.00,0.00,9.20,0.19)
MAT <- data.frame(matrix(MAT, ncol = 6, byrow = FALSE))
MAT[MAT == 0] <- NA
M <- data.frame()
for (i in (1:nrow(MAT)))
{
for(j in (1:ncol(MAT)))
{
if(!is.na(MAT))
{
M[i,j] <- MAT[i,j]
}
else
M[i,j] <- rbeta(1,0.1,1)
}
}
But this does not work.
Then I tried this:
MAT[is.na(MAT)] <- rbeta(1,0.1,1)
The problem with the second attempt is that the NAs are replaced with a value
which is the same for all NA elements, yet I want them to be different. Please
help!
Thank you
Sibu
____________________________________________________________
South Africas premier free email service - www.webmail.co.za
For super low premiums, click here.
http://www.dialdirect.co.za/landing/oct/1/?vdn=15752
______________________________________________
R-help at 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.
More information about the R-help
mailing list