我意識到這個主題有很多問題,但我無法通過查看各種答案來解決我的問題。我有一個DF - 的提取物,其中附加如下:按因子分解df,應用函數並返回合併的df
ID = as.factor(c("1","1","1","1","1",
"2","2","2",
"3","3","3","3",
"4","4","4","4","4"))
AdDate = c("2010-03-04", "2010-04-05", "2011-01-23", "2011-03-20", "2012-07-08",
"2010-12-02", "2011-05-17", "2011-09-11",
"2010-04-11", "2010-05-15", "2011-02-22", "2011-09-23",
"2009-10-04", "2010-02-15", "2010-08-17", "2011-06-20", "2012-04-08")
OpofInterest = c("FALSE", "FALSE", "TRUE", "FALSE", "FALSE",
"FALSE", "TRUE", "FALSE",
"FALSE", "FALSE", "TRUE", "FALSE",
"FALSE", "FALSE", "TRUE", "FALSE", "FALSE")
df = data.frame(ID, AdDate, OpofInterest)
什麼然後我想要做的是(在該實施例4)通過ID的DF分成多個dataframes的,然後應用下面的功能根據AdDate爲每個人(ID)分配其他情節(每行)是否在手術前(手術前),手術相同(每次手術)或手術後(手術後)。我是新來的R和編程,並在下面產生了一個功能。實際上,我有成千上萬的ID和劇集,以及大約80列,所以我不能單獨分組和應用我經過一些調整後才能工作的功能。
prepostassignment <- function (df) {
df_OpofInterest = subset(df,(df["OpofInterest"] == "TRUE"))
for (i in 1:nrow(df)) {
if (df$AdDate[i] < df_OpofInterest$AdDate) {
df$Pre_Post_Assignment[i] = "Pre"
} else if (df$AdDate[i] == df_OpofInterest$AdDate) {
df$Pre_Post_Assignment[i] = "Per"
} else if (df$AdDate[i] > df_OpofInterest$AdDate) {
df$Pre_Post_Assignment[i] = "Post"
}
}
}
我已經通過,tapply,骨料,ddply發揮四周,似乎無法拿出一個 解決方案。我使用的手動子集的功能時,也已經得到以下錯誤信息:
遺漏值,其中TRUE/FALSE需要
我已經在這個閱讀起來很好,但無法理解它是怎麼回事錯在我的特殊代碼
我想落得如下:
ID = as.factor(c("1","1","1","1","1",
"2","2","2",
"3","3","3","3",
"4","4","4","4","4"))
AdDate = c("2010-03-04", "2010-04-05", "2011-01-23", "2011-03-20", "2012-07-08",
"2010-12-02", "2011-05-17", "2011-09-11",
"2010-04-11", "2010-05-15", "2011-02-22", "2011-09-23",
"2009-10-04", "2010-02-15", "2010-08-17", "2011-06-20", "2012-04-08")
OpofInterest = c("FALSE", "FALSE", "TRUE", "FALSE", "FALSE",
"FALSE", "TRUE", "FALSE",
"FALSE", "FALSE", "TRUE", "FALSE",
"FALSE", "FALSE", "TRUE", "FALSE", "FALSE")
Pre_Post_Assignment = c("Pre", "Pre", "Per", "Post", "Post",
"Pre", "Per", "Post",
"Pre", "Pre", "Per", "Post",
"Pre", "Pre", "Per", "Post", "Post")
df_new = data.frame(ID, AdDate, OpofInterest, Pre_Post_Assignment)
任何幫助將不勝感激。
謝謝。
什麼是你的第二個代碼塊中的'df_OpofInterest'和'df_TAVI'? – josliber
道歉,df_TAVI應該是df_OpofInterest。爲了獲得在函數 – sgurwin
中使用的AdDate,我爲子集「利益操作」進行了子集。爲什麼您要從類「字符」的列開始(然後轉換爲「因子」)?不應該是'整數',日期是'日期',OpofInterest是'邏輯'? –