R清理数据帧的聪明方法
我有一个包含两列的数据框,一个索引列,它对第二个数据框中的行进行索引。这些行都包含一个特定的事件。这是哪一个事件,在第二列中编码,在这里命名为R清理数据帧的聪明方法,r,R,我有一个包含两列的数据框,一个索引列,它对第二个数据框中的行进行索引。这些行都包含一个特定的事件。这是哪一个事件,在第二列中编码,在这里命名为code\u start\u stop 例如: index <- c(769, 766, 810, 813, 830, 842, 842, 892, 907, 944) code_start_stop <- c(2006, 2001, 2004, 1001, 1004, 2001, 1001, 1006, 2004, 1004) replace
code\u start\u stop
例如:
index <- c(769, 766, 810, 813, 830, 842, 842, 892, 907, 944)
code_start_stop <- c(2006, 2001, 2004, 1001, 1004, 2001, 1001, 1006, 2004, 1004)
replace_all <- data.frame(index, code_start_stop)
index你的问题有点让人困惑,如果我弄错了,请纠正我。
以下方面应起作用:
startm <- 2006 #startmarker
endm <- 1006 #endmarker
#look for row that contains markers
index1 <- which(replace_all[,2] == startm)
index2 <- which(replace_all[,2] == endm)
#subset accordingly
replace_all <- replace_all[-(index1:index2),]
startm该解决方案现在基于maRtin的建议,似乎效果不错
我对所有开始和结束标记对执行以下操作:
to_delete <- c()
## Care = 2001/1001
startm1 <- 2001
endm1 <- 1001
index1 <- which((replace_all[,2] == startm1))
index2 <- which((replace_all[,2] == endm1))
if(length(index1) !=0){
for (i in 1:length(index1)){
if (index2[i]-index1[i]>1){
to_delete <- c(to_delete, (((index1[i])+1):((index2[i])-1)))
}
}
}
谢谢!但是,我首先有一对开始和结束标记:startm1您可以简单地循环那些对index
和code\u start\u stop
在这里有不同的长度,因此不能用当前代码创建replace\u all
。
if (length(to_delete) != 0){
replace_all <- replace_all[-to_delete,]
}
replace_all <- replace_all[,1]
}