使用for循环从一个基于off的值创建多个数据帧

使用for循环从一个基于off的值创建多个数据帧

本文介绍了使用for循环从一个基于off的值创建多个数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大数据框,我想使用for循环将其转换成较小的子集数据框。我希望新数据框基于大/父数据框中的一列中的值。这是一个示例

I have a large data frame that I would like to convert in to smaller subset data frames using a for loop. I want the new data frames to be based on the the values in a column in the large/parent data frame. Here is an example

x<- 1:20
y <- c("A","A","A","A","A","A","A","A","B","B","B","B","B","B","B","B","B","C","C","C")
df <- as.data.frame(cbind(x,y))

好,现在我要三个数据帧,一个是x和y列,但只有y == A时,第二个,其中y ==
B等,因此最终结果将是3个新数据帧df.A,df.B和df.C。我意识到,通过for循环很容易做到这一点,但是我的实际数据具有很多y值,因此使用for循环(或类似方法)会很好。

ok, now I want three data frames, one will be columns x and y but only where y == "A", the second where y=="B" etc etc. So the end result will be 3 new data frames df.A, df.B, and df.C. I realize that this would be easy to do out of a for loop but my actual data has a lot of levels of y so using a for loop (or similar) would be nice.

谢谢!

推荐答案

如果要在循环中创建单独的对象,可以使用 assign 。我使用 unique 是因为您说您有很多级别。

If you want to create separate objects in a loop, you can use assign. I used unique because you said you had many levels.

 for(i in unique(df$y)) {
        nam <- paste("df", i, sep = ".")
        assign(nam, df[df$y==i,])
        }

> df.A
  x y
1 1 A
2 2 A
3 3 A
4 4 A
5 5 A
6 6 A
7 7 A
8 8 A
> df.B
    x y
9   9 B
10 10 B
11 11 B
12 12 B
13 13 B
14 14 B

这篇关于使用for循环从一个基于off的值创建多个数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 17:52