Home > database >  R: Create Data Frame for Each Unique Factor
R: Create Data Frame for Each Unique Factor

Time:02-19

I am working with the R programming language.

I wrote the following code which creates 50 random data sets, indexed by "i":

results <- list()

for (i in 1:50) {


x_i = rnorm(100,1,1)

y_i = rnorm(100,1,1)

z_i = x_i^2   y_i^2 - 10*(cos(2*pi*x_i)   cos(2*pi*y_i))

my_data_i = data.frame(x_i, y_i, z_i)

my_data_i$iteration = i

 results[[i]] <- my_data_i

}



results_df <- do.call(rbind.data.frame, results)

X<-split(results_df, results_df$iteration)

I tried to output the results from this code into 2 different formats:

1)

head(results_df)
          x_i       y_i        z_i iteration
1  1.40961448 1.2457421 11.7016599         1
2 -0.57995713 0.9573615  0.3739812         1
3  1.41691144 1.5326736 22.8146703         1
4  2.37191691 1.4067927 22.8714206         1
5  0.05199839 1.6663260 -1.6731452         1
6  1.55276440 1.1400349  6.7936643         1

2)

head(X)

$`47`
               x_i          y_i          z_i iteration
4601  0.1934291501 -0.276897671  -1.68399306        47
4602 -0.9259593146  0.147881940 -14.04299215        47
4603  1.7537230121  0.037046456  -6.88729779        47
4604 -0.5262735315  1.519582764  22.37454393        47
4605  3.8616108889  0.126078408   1.45304131        47
4606  0.7257319810  1.109770193  -4.43714870        47

My Question: Is it possible to create 50 individual datasets for each unique "index"? For example : my_data_1, my_data_2, my_data_3, etc.

Thanks!

CodePudding user response:

Yes, you can, though you shouldn't.

The easiest way to accomplish this bad idea is with list2env

## name appropriately and put them in the global environment
names(results) = paste0("my_data_", seq_along(results))
list2env(results, envir = .GlobalEnv)

(I'll also note that your X is the same as your results. results is a list of data frames, results_df is all those data frames combined into 1, and X you split back to where you started with results.)

For discussion of why you shouldn't do this, see my answer at How to make a list of data frames?. Generally it's much easier, less bug-prone, and more readable to use data frames in a list or combined into one than as individual sequentially named objects.

  • Related