如何循环修改R中的多个数据帧 [英] How to loop through and modify multiple data frames in R

查看:125
本文介绍了如何循环修改R中的多个数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数据帧A,B,C,...并且想要以相同的方式修改每个数据帧,例如。所有数据框中存在因子的重新排序因子水平:

  A = data.frame(x = c('x','x','y','y','z','z'))
B = data.frame(x = c('x','y' z'))
C = data.frame(x = c('x','x','x','y','y','y','z','z' 'z'))

A $ x = factor(A $ x,levels = c('z','y','x'))
B $ x = factor B $ x,levels = c('z','y','x'))
C $ x = factor(C $ x,levels = c('z','y','x' ))

如果有大量数据框和/或许多修改完成,这将变得很费力。如何简洁地使用循环或更好的东西?对于(列表(A,B,C)中的D),一个简单的方法,例如

  {
D $ x =因子(D $ x,levels = c('z','y','x'))
}

不起作用,因为它不会修改原始数据帧。



编辑:添加A,B和C的定义它可以重现。

解决方案

有关R的一件事是,关于作业 < - 是传递的,而 = 不是。因此,如果你的数据框架在这方面都是一样的,你应该可以这样做:

  A $ (C $ x,levels = c('z','y','x'))


I have data frames A, B, C, ... and want to modify each data frame in the same way, e.g. re-ordering factors levels of a factor which is present in all of the data frames:

A = data.frame( x=c('x','x','y','y','z','z') )
B = data.frame( x=c('x','y','z') )
C = data.frame( x=c('x','x','x','y','y','y','z','z','z') )

A$x = factor( A$x, levels=c('z','y','x') )
B$x = factor( B$x, levels=c('z','y','x') )
C$x = factor( C$x, levels=c('z','y','x') )

This gets laborious if there are lots of data frames and/or lots of modifications to be done. How can I do it concisely, using a loop or something better? A straightforward approach like

for ( D in list( A, B, C ) ) {
D$x = factor( D$x, levels=c('z','y','x') )
}

does not work, because it doesn't modify the original data frames.

EDIT: added definitions of A, B, and C to make it reproducible.

解决方案

One thing to note about R is that, with respect to assignment, <- is transitive, whereas = is not. Thus, if your data frames are all the same in this respect, you should be able to do something like this:

A$x <- B$x <- C$x <- factor( C$x, levels=c('z','y','x') )

这篇关于如何循环修改R中的多个数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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