R Adding random sample -


i have text file like

1 2 1 3 1 2 3 5 11 1 2 3 5 12 . . 18k rows 

and want generate random sample between 0, , 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 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 output in txt file  fileconn <- file("unexample30v2.txt")  writelines(res,fileconn)  close(fileconn) 

but gave me unique value 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 

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$ 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -