且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何为R for循环中的每次迭代创建一个新的数据框?

更新时间:2022-10-27 22:58:35

您可以使用:

  n<-ncol(weekly_df)list_df<-lapply(名称(weekly_df)[-c(n-1,n)],函数(x)cbind(weekly_df [x],weekly_df [c(n-1,n)])) 

这将返回一个数据框列表,通常***将数据保留在列表中,因为它更易于管理并且避免在全局环境中创建大量变量,但是如果您希望将它们作为单独的数据框,则可以命名列表并使用 list2env .

  list_df<-paste0('数据',seq_along(list_df))list2env(list_df,.GlobalEnv) 

I am attempting to create a new dataframe based on the results from each iteration of a for loop in R. I have a "weekly_df" which has weekly values for multiple columns. I would like to create a new dataframe which contains the values from each column (based on the iteration number) along with the date columns (Year and Week, which are always the last two columns).

Currently, I have the following data columns (which have numeric values for each row)...

A1 Score, A1 Volume, A2 Score, A2 Volume, A3 Score, A3 Volume, Year, Week

So essentially I want to create a new dataframe for each column up until 'Year'...

A1 Score, Year, Week

A1 Volume, Year, Week

So on and so fourth, but I am unsure how to loop my data to create a new dataframe for each of these. I currently have the following...

for (i in 1:(length(names(weekly_df)) -2)) {
print(weekly_df[,c(i,((length(names(weekly_df))) -1), (length(names(weekly_df))))]) }

This prints the correct 'tibble' for each of the dataframes that I want but I'm unsure how to transform these into saved dataframes in my environment to be used later on.

Here is a reproducible dataset:

A1 Score, A1 Volume, A2 Score, A2 Volume, A3 Score, A3 Volume, Year, Week

1, 2, 3, 4, 5, 6, 2016, 1

7, 8, 9, 10, 11, 12, 2016, 2

13, 14, 15, 16, 17, 18, 2016, 3

And my desired output is each of the following as a dataframe in my environment:

A1 Score, Year, Week

1, 2016, 1

7, 2016, 2

13, 2016, 3

A1 Volume, Year, Week

2, 2016, 1

8, 2016, 2

14, 2016, 3

A2 Score, Year, Week

3, 2016, 1

9, 2016, 2

15, 2016, 3

... so and so fourth as to create a dataframe from each column.

You can use :

n <- ncol(weekly_df)
list_df <- lapply(names(weekly_df)[-c(n-1, n)], function(x) 
               cbind(weekly_df[x], weekly_df[c(n-1, n)]))

This will return you a list of dataframes, usually it is better to keep data in a list since it is easier to manage and avoids creating lot of variables in the global environment but if you want them as separate dataframes, you can name the list and use list2env.

list_df <- paste0('data', seq_along(list_df))
list2env(list_df, .GlobalEnv)