2012-07-04 96 views
1

我经常发现自己需要基于某些条件将少量基于规则的转换应用于数据帧,通常是具有特定值的固定数量的字段。转换可以修改任意数量的列,通常是一到三个。与数据帧中的总行数相比,这些转换涉及的行数很少。目前我正在使用ddply,但由于ddply修改了所有行,所以性能不足。稀疏数据帧子集的转换

我正在寻找一种方法来以优雅,通用的方式解决这个问题,利用只有少数行需要更改的事实。以下是我正在处理的转换类型的简化示例。

df <- data.frame(Product=gl(4,10,labels=c("A","B", "C", "D")), 
       Year=sort(rep(2002:2011,4)), 
       Quarter=rep(c("Q1","Q2", "Q3", "Q4"), 10), 
       Sales=1:40)   
> head(df) 
    Product Year Quarter Sales 
1  A 2002  Q1  1 
2  A 2002  Q2  2 
3  A 2002  Q3  3 
4  A 2002  Q4  4 
5  A 2003  Q1  5 
6  A 2003  Q2  6 
> 
transformations <- function(df) { 
    if (df$Year == 2002 && df$Product == 'A') { 
     df$Sales <- df$Sales + 3 
    } else if (df$Year == 2009 && df$Product == 'C') { 
     df$Sales <- df$Sales - 10 
     df$Product <- 'E' 
    } 
    df 
} 

library(plyr) 
df <- ddply(df, .(Product, Year), transformations) 

> head(df) 
    Product Year Quarter Sales 
1  A 2002  Q1  4 
2  A 2002  Q2  5 
3  A 2002  Q3  6 
4  A 2002  Q4  7 
5  A 2003  Q1  5 
6  A 2003  Q2  6 

硬编码的条件句insted的我使用的条件和转换功能成对列表,例如,下面的代码,但是这不是一个有意义的改善。

transformation_rules <- list(
    list(
    condition = function(df) df$Year == 2002 && df$Product == 'A', 
    transformation = function(df) { 
     df$Sales <- df$Sales + 3 
     df 
    } 
) 
) 

有什么更好的方法来解决这个问题?

回答

2

我不认为你需要使用plyr来解决这个问题。我想你可以简单地使用ifelse()并利用R矢量化并获得相同结果的事实。

由于您的函数直接修改Sales列,所以在运行plyr之前,我制作了它的副本:df2 <- df。我也有我的例子做一个新的列Sales2,而不是覆盖Sales列。

然后重写你的函数是这样的:

df2$Sales2 <- with(df2, ifelse(Year == 2002 & Product == "A", Sales + 3, 
         ifelse(Year == 2009 & Product == "C", Sales - 10, Sales))) 

和测试的输出是否等于:

> all.equal(df$Sales, df2$Sales2) 
[1] TRUE 

,并比较了矢量版本,避免两个节目之间的系统时间ddply要快得多:

> system.time(df <- ddply(df, .(Product, Year), transformations)) 
    user system elapsed 
    0.012 0.000 0.012 
> system.time(df2$Sales2 <- with(df2, ifelse(Year == 2002 & Product == "A", Sales + 3, 
+       ifelse(Year == 2009 & Product == "C", Sales - 10, Sales)))) 
    user system elapsed 
     0  0  0 

所以,除非我失踪somethi ng - 你可以在这里一起避免plyr,并获得一些不错的速度提升。如果ifelse()证明速度太慢,你可以写出一些布尔函数来更快,但我怀疑这是必要的。

+0

Chase,修改Sales列的例子就是这样 - 一个例子。实际上,我需要时常修改几列。我已经更新了这个问题来反映这一点。你会建议重复ifelse()条件吗? – Sim