我有一个包含一组零件和测试结果的数据框。零件在 3 个地点(北中心和南)进行测试。有时这些部件会被重新测试。我想最终创建一些图表,将零件第一次测试的结果与第二次(或第三次等)测试的结果进行比较,例如查看测试仪的可重复性。
作为一个例子,我想出了下面的代码。我已经从 morley 数据集中明确删除了“实验”列,因为这是我正在有效地尝试重新创建的列。该代码有效,但是似乎必须有一种更优雅的方法来解决这个问题。有什么想法吗?
编辑 - 我意识到给出的示例对于我的实际需求过于简单(我试图尽可能轻松地生成一个可重现的示例)。
新示例:
part<-as.factor(c("A","A","A","B","B","B","A","A","A","C","C","C"))
site<-as.factor(c("N","C","S","C","N","S","N","C","S","N","S","C"))
result<-c(17,20,25,51,50,49,43,45,47,52,51,56)
data<-data.frame(part,site,result)
data$index<-1
repeat {
if(!anyDuplicated(data[,c("part","site","index")]))
{ break }
data$index<-ifelse(duplicated(data[,1:2]),data$index+1,data$index)
}
data
part site result index
1 A N 17 1
2 A C 20 1
3 A S 25 1
4 B C 51 1
5 B N 50 1
6 B S 49 1
7 A N 43 2
8 A C 45 2
9 A S 47 2
10 C N 52 1
11 C S 51 1
12 C C 56 1
旧示例:
#Generate a trial data frame from the morley dataset
df<-morley[,c(2,3)]
#Set up an iterative variable
#Create the index column and initialise to 1
df$index<-1
# Loop through the dataframe looking for duplicate pairs of
# Runs and Indices and increment the index if it's a duplicate
repeat {
if(!anyDuplicated(df[,c(1,3)]))
{ break }
df$index<-ifelse(duplicated(df[,c(1,3)]),df$index+1,df$index)
}
# Check - The below vector should all be true
df$index==morley$Expt
最佳答案
我认为这是 make.unique
的工作,经过一些操作。
index <- 1L + as.integer(sub("\\d+(\\.)?","",make.unique(as.character(morley$Run))))
index <- ifelse(is.na(index),1L,index)
identical(index,morley$Expt)
[1] TRUE
关于重新枚举具有唯一值的数据帧中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32393814/