如何在R数据帧中的列之间循环,并在每次迭代中使用列名创建一个新的数据帧? [英] How to loop through the columns in an R data frame and create a new data frame using the column name in each iteration?

查看:36
本文介绍了如何在R数据帧中的列之间循环,并在每次迭代中使用列名创建一个新的数据帧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个R数据帧dftotal

I have an R data frame dftotal

i  A  B C  D
1  4 15 4 12
2 13  4 4  7 
3  1  1 3  8 
4  3 11 1  9 

我想编写一个遍历列(A,B,C,D)并每次创建一个新数据帧的循环,以便为每个列创建一个数据帧:

I want to write a loop that goes through the columns (A,B,C,D) and creates a new data frame each time, so that I have a data frame for each column:

dfA:

i  A  
1  4 
2 13  
3  1   
4  3 

和dfB:

i  B 
1 15 
2  4 
3  1  
4 11 

等等...

我尝试过:

List <- colnames(dftotal)
List <- List[-1]
for (j in length(List)) 
    {
      df <- data.frame(dftotal$i,dftotal[List[j]]) 
      assign(paste("df",List[j]), df)

    }

但这仅返回列表中最后一列的数据框.似乎已经覆盖了在循环中创建的其他数据帧.

But that returned a data frame only for the last column in my list. It seems to have overwritten the other data frames that were created in the loop.

df <- data.frame(dftotal$i,dftotal[List[1]]) 
      assign(paste("df",List[1]), df)

工作正常,当我逐列手动运行它时.

Works fine, when I run it column by column manually.

我做错了什么?

推荐答案

作记录-回答您做错了什么问题:

For the record - replying to the question of what you are doing wrong:

for(长度为j(列表))

应该是

for(j in 1:length(List))

这篇关于如何在R数据帧中的列之间循环,并在每次迭代中使用列名创建一个新的数据帧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆