Reputation: 91
I have text file like
1 2
1 3
1 2 3 5 11
1 2 3 5 12
.
.
up to 18k rows
and I want to generate random sample between 0, and 1, like
1 0.31 2 0.15
1 0.93 3 0.84
1 0.62 2 0,76 3 0.34 5 0.31 11 0.11
1 0.55 2 0.54 3 0.62 5 0.44 12 0.54
.
.
I used the follow code
Lines1 <- readLines("Example30v2.txt")
lst1 <- lapply(Lines1,function(x)
{ x1 <-scan(text=x,nmax=1000,quiet=TRUE);
dat1<-as.data.frame(matrix(x1,ncol=1,byrow=TRUE))
})
nm1 <- (unlist(lapply(lst1,`[`,1),use.names=FALSE))
set.seed(48)
vec1 <- sample(seq(0,1,by=0.01),length(nm1),replace = TRUE)
names(vec1) <- nm1
res <- sapply(lst1,function(x)
{ x$V2 <- vec1[as.character(x$V1)];
paste(as.vector(t(x)),collapse=" ")
})
##Save the output in a txt file
fileConn <- file("unExample30v2.txt")
writeLines(res,fileConn)
close(fileConn)
but it gave me unique value for each number.
1 0.58 2 0.03
1 0.58 3 0.38
1 0.58 2 0.03 3 0.38 5 0.99 11 0.03
1 0.58 2 0.03 3 0.38 5 0.99 12 0.91
Upvotes: 0
Views: 106
Reputation: 1581
To generate a random sample of size 20 in the set [1,0] you can use following code
u <- runif(20)
when you call it for each number each time you should get different values.
you will need to loop on your numbers in the vector and call runif(yournumber)
Upvotes: 1
Reputation: 35324
set.seed(1);
system('cat -vet Example30v2.txt;');
## 1 2$
## 1 3$
## 1 2 3 5 11$
## 1 2 3 5 12$
input <- as.matrix(unname(read.table('Example30v2.txt',sep=' ',fill=T)));
input;
## [,1] [,2] [,3] [,4] [,5]
## [1,] 1 2 NA NA NA
## [2,] 1 3 NA NA NA
## [3,] 1 2 3 5 11
## [4,] 1 2 3 5 12
output <- matrix(rbind(c(t(input)),round(ifelse(is.na(c(t(input))),NA,runif(nrow(input)*ncol(input))),2)),nrow(input),byrow=T);
output;
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
## [1,] 1 0.27 2 0.37 NA NA NA NA NA NA
## [2,] 1 0.90 3 0.94 NA NA NA NA NA NA
## [3,] 1 0.21 2 0.18 3 0.69 5 0.38 11 0.77
## [4,] 1 0.50 2 0.72 3 0.99 5 0.38 12 0.78
writeLines(apply(output,1,function(x) paste(na.omit(x),collapse=' ')),'unExample30v2.txt');
system('cat -vet unExample30v2.txt;');
## 1 0.27 2 0.37$
## 1 0.9 3 0.94$
## 1 0.21 2 0.18 3 0.69 5 0.38 11 0.77$
## 1 0.5 2 0.72 3 0.99 5 0.38 12 0.78$
Upvotes: 2