【发布时间】:2014-01-15 19:49:25
【问题描述】:
我知道关于这个主题有很多问题,但我无法通过查看各种答案来解决我的问题。我有一个 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)
然后我想要做的是按 ID 将 df 拆分为多个数据帧(本例中为 4 个),然后应用下面的函数来分配其他情节(每行)是否在之前(手术前) ,相同的(每次手术),或基于 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"
}
}
}
我玩过 by、tapply、aggregate、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是什么? -
抱歉,df_TAVI 应该是 df_OpofInterest。我正在对“感兴趣的操作”进行子集化以获得用于函数的 AdDate
-
为什么从
character类的列开始(然后转换为factor)? ID不应该是integer,日期是Date,OpofInterest是logical吗? -
我认为我可能需要在某些时候拆分 df 的因素。但是,是的,你是对的。
标签: r