我正在尝试根据多个标准上的两个 data.frames 的交集来填充二进制向量。
我有代码工作,但我觉得只是为了获得二进制向量而内存过多。
当我将代码应用于我的完整数据(40 毫米以上行)时。我开始有记忆问题。
有没有更简单的方法来产生向量?
这是一些样本数据(例如,子样本将仅包括完整样本中的 obs):
ob1_1 <- as.data.frame(cbind(c(1999),c("111","222","666","777")),stringsAsFactors=FALSE)
ob2_1 <- as.data.frame(cbind(c(2000),c("111","333","555","777")),stringsAsFactors=FALSE)
ob3_1 <- as.data.frame(cbind(c(2001),c("111","222","333","777")),stringsAsFactors=FALSE)
ob4_1 <- as.data.frame(cbind(c(2002),c("111","444","555","777")),stringsAsFactors=FALSE)
full_sample <- rbind(ob1_1,ob2_1,ob3_1,ob4_1)
colnames(full_sample) <- c("yr","ID")
ob1_2 <- as.data.frame(cbind(c(1999),c("111","222","777")),stringsAsFactors=FALSE)
ob2_2 <- as.data.frame(cbind(c(2000),c("333")),stringsAsFactors=FALSE)
ob3_2 <- as.data.frame(cbind(c(2001),c("888")),stringsAsFactors=FALSE)
ob4_2 <- as.data.frame(cbind(c(2002),c("111","444","555","777")),stringsAsFactors=FALSE)
sub_sample <- rbind(ob1_2,ob2_2,ob3_2,ob4_2)
colnames(sub_sample) <- c("yr","ID")
这是我的工作代码:
q_intersect <- ""
q_intersect <- paste(q_intersect , "select a.yr, a.ID ", sep=" ")
q_intersect <- paste(q_intersect , "from full_sample a ", sep=" ")
q_intersect <- paste(q_intersect , "intersect ", sep=" ")
q_intersect <- paste(q_intersect , "select b.yr, b.ID ", sep=" ")
q_intersect <- paste(q_intersect , "from sub_sample b ", sep=" ")
q_intersect <- trim(gsub(" {2,}", " ", q_intersect ))
intersect_temp <- cbind(sqldf(q_intersect ),1)
colnames(intersect_temp ) <- c("yr","ID","in_both")
q_expand <- ""
q_expand <- paste(q_expand , "select in_both ", sep=" ")
q_expand <- paste(q_expand , "from full_sample a ", sep=" ")
q_expand <- paste(q_expand , "left join intersect_temp b ", sep=" ")
q_expand <- paste(q_expand , "on a.yr=b.yr ", sep=" ")
q_expand <- paste(q_expand , "and a.ID=b.ID ", sep=" ")
q_expand <- trim(gsub(" {2,}", " ", q_expand ))
solution <- as.integer(sqldf(q_expand)[,1])
solution [is.na(solution )] <- 0
提前感谢您的帮助!