我經常發現自己需要基於某些條件將少量基於規則的轉換應用於數據幀,通常是具有特定值的固定數量的字段。轉換可以修改任意數量的列,通常是一到三個。與數據幀中的總行數相比,這些轉換涉及的行數很少。目前我正在使用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
}
)
)
有什麼更好的方法來解決這個問題?
Chase,修改Sales列的例子就是這樣 - 一個例子。實際上,我需要時常修改幾列。我已經更新了這個問題來反映這一點。你會建議重複ifelse()條件嗎? – Sim