I want to rewrite some of the first lines from this question, and I can't figure out why my sapply
line isn't working.
I want to turn these lines:
cols <- sample(c(1:5), 1)
label <- rep(paste0("label ", seq(from=1, to=10)))
mydata <- data.frame(label)
for (i in 1:cols) {mydata[,i+1] <- sample(c(1:10), 10)}
into:
cols <- sample(c(1:5), 1)
mydata <- data.frame(rep(paste0("label ", seq(1,10))))
sapply(1:cols, function(x) { mydata[,(x+1)] <- sample(c(1:10), 10) } )
but for some reason that sapply
line gives me a new columns would leave holes after existing columns
error, and I don't know why.
I've also tried
sapply(1:cols, function(x) { mydata[,(x+1)] <- sample(c(1:10), 10); mydata } )
Map(function(x, mydata1) {mydata1[,(x+1)] <- sample(c(1:10), 10)}, x = 1:cols, mydata1 = mydata)