我有一個廣泛的調查數據集。對於一個特定的問題,在原始數據中創建了一組變量來表示調查問題在特定月份被問到的不同事實。使用數據表對子集執行操作
我希望創建一個具有月份不變名稱的新變量集合;這些變量的值將對應於所觀察月份的月份變量問題的值。
請看一個例子/虛構數據集:
require(data.table)
data <- data.table(month = rep(c('may', 'jun', 'jul'), each = 5),
may.q1 = rep(c('yes', 'no', 'yes'), each = 5),
jun.q1 = rep(c('breakfast', 'lunch', 'dinner'), each = 5),
jul.q1 = rep(c('oranges', 'apples', 'oranges'), each = 5),
may.q2 = rep(c('econ', 'math', 'science'), each = 5),
jun.q2 = rep(c('sunny', 'foggy', 'cloudy'), each = 5),
jul.q2 = rep(c('no rain', 'light mist', 'heavy rain'), each = 5))
在此次調查中,有真的只有兩個問題: 「Q1」 和 「Q2」。這些問題中的每一個都被反覆詢問了幾個月。但是,只有在數據中觀察到的月份與特定月份的調查問題相匹配時,觀察結果才包含有效的答覆。
例如:對於「May」中的任何觀察,「may.q1」被觀察爲「是」。我想要一個新的「Q1」變量來表示「may.q1」,「jun.q1」和「jul.q1」。當月份爲「可」時,「Q1」的值將取「may.q1」的值,當月份爲「jun」時,「Q1」的值將取值「jun.q1」 。
如果我嘗試並使用數據表手工做到這一點,我想是這樣的:
mdata <- data[month == 'may', c('month', 'may.q1', 'may.q2'), with = F]
setnames(mdata, names(mdata), gsub('may\\.', '', names(mdata)))
我想這個重複「通過=月」。
如果我是使用「plyr」包用於數據幀,我會解決使用以下方法:
require(plyr)
data <- data.frame(data)
mdata <- ddply(data, .(month), function(dfmo) {
dfmo <- dfmo[, c(1, grep(dfmo$month[1], names(dfmo)))]
names(dfmo) <- gsub(paste0(dfmo$month[1], '\\.'), '', names(dfmo))
return(dfmo)
})
使用data.table方法任何幫助將不勝感激,如我的數據很大。謝謝。
哇..我覺得憑着這個!真棒。 – Arun 2013-04-22 18:56:58
MatthewDowle,這肯定比(我的)融合+演員快。我嘗試了一個更大的數據。我不是在哪裏接近...... 1e5 * 100列需要23秒,而這隻需要不到一秒鐘! – Arun 2013-04-22 19:56:38