Create data.frame form for loop

taobien <- function(obs,n){
  stt<-1:obs
  tapbien <-cbind(stt)
  for (i in 1:n){
    bien <-round(rnorm(obs,10,2),1)
    bien<-data.frame(bien)
    colnames(bien)<-paste0("Bien",i)
    tapbien <-cbind(tapbien,bien)    
  }
}
head(tapbien)

I have this code to create data.frame from loop, but it not working.
Help me, fix it.

Is this what you want to do? The data frame tapbien only exists inside the function taobien().

taobien <- function(obs,n){
  stt<-1:obs
  tapbien <-cbind(stt)
  for (i in 1:n){
    bien <-round(rnorm(obs,10,2),1)
    bien<-data.frame(bien)
    colnames(bien)<-paste0("Bien",i)
    tapbien <-cbind(tapbien,bien)    
  }
  return(tapbien)
}
NewDF <- taobien(5,4)
head(NewDF)
#>   stt Bien1 Bien2 Bien3 Bien4
#> 1   1  11.6   9.6   7.4  10.4
#> 2   2  10.7  12.5   9.4  12.5
#> 3   3   7.8  10.7   8.3  13.6
#> 4   4   9.1   9.2  10.8  10.3
#> 5   5  11.5  11.9  11.9   8.5

Created on 2022-07-14 by the reprex package (v2.0.1)

1 Like

Hi @tommyteo,
Welcome to the RStudio Community Forum.

It’s not entirely clear what your required output is, but this code produces a dataframe:

set.seed(1984)

taobien <- function(obs,n){
  stt <- c(1:obs)
  tapbien <- cbind(stt)
  for (i in 1:n){
    bien <-round(rnorm(obs,10,2),1)
    bien <- data.frame(bien)
    colnames(bien)<-paste0("Bien",i)
    tapbien <-cbind(tapbien,bien)    
  }
  return(tapbien)
}

keep <- taobien(20,5)

head(keep)

  stt Bien1 Bien2 Bien3 Bien4 Bien5
1   1  10.8  12.5  10.1   8.5  10.4
2   2   9.4  10.9  11.6  11.3  11.1
3   3  11.3   8.7   9.8  13.3   9.1
4   4   6.3  11.8   7.3   9.3   7.1
5   5  11.9  10.0  12.5  13.2  10.3
6   6  12.4  10.5  12.4   9.4  12.3

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.