以下のforループのベクトル解がありますか?これは、医療施設への入院データを含む大規模なデータセットです。forループ用のベクトル化された解答
EDITED
library(lubridate)
dateSeq <- as.Date(c("2015-01-01", "2015-02-01"))
admissionDate <- as.Date(c("2015-01-03", "2015-01-06", "2015-01-10", "2015-01-05", "2015-01-07", "2015-02-03", "2015-02-06"))
Dfactor <- c("elective", "acute", "elective", "acute", "acute", "elective", "acute")
Dfactor <- factor(Dfactor)
df <- data.frame(admissionDate, Dfactor)
# loop through large dataset collecting tabulated data from a factorised vector for each month (admissions date) based on 'dateSeq'
Dfactorsums <- c()
for (i in 1:length(dateSeq)) {
monthSub <- df[(df$admissionDate >= as.Date(timeFirstDayInMonth(dateSeq[i]))) & (df$admissionDate <= as.Date(timeLastDayInMonth(dateSeq[i]))), ]
x <- table(monthSub$Dfactor)
Dfactorsums[i] <- as.numeric((x[1]))
}
print(Dfactorsums)
# Outcome = [1] 3 1
# Question is rather than use a for loop is there a 'vectorized' solution.
この例に基づいて、小さな再現可能な例と予想される出力を示してください。 'df'とは何ですか? – akrun
毎月 'Dfactor'の2番目の値の出現回数が必要なようです。そうですか? – rosscova
右。まったく。より完全な例を少し提供します。 –