R添加随机样本

时间:2015-05-30 23:08:38

标签: r random-seed

我有像

这样的文本文件
1 2
1 3
1 2 3 5 11
1 2 3 5 12
.
.
up to 18k rows

我希望在0和1之间生成随机样本,如

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
.
.

我使用了以下代码

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)

但它给了我每个数字的唯一价值。

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

2 个答案:

答案 0 :(得分:2)

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$

答案 1 :(得分:1)

要在集合[1,0]中生成大小为20的随机样本,您可以使用以下代码

  u <- runif(20)

每当你得到不同的值时,你为每个号码调用它。

你需要在向量中循环你的数字并调用runif(你的数字)

enter image description here

相关问题