通过将一列的值与第二列的值匹配来显示该列的对应值

Displaying corresponding value of a column by matching it to value of the second column

生成如下两个数据集:

  H<-data.frame(replicate(10,sample(0:20,10,rep=TRUE)))  
  G<-data.frame(replicate(10,sample(0:20,10,rep=TRUE)))  
  H[c(2,3,7,9),9]<-NA
  G[c(1,5,7,8),9]<-NA
  H$diff<-H$X10-H$X9
  G$diff<-G$X10-G$X9
  H$perc<-round((H$diff/H$X10)*100,1)
  G$perc<-round((G$diff/G$X10)*100,1)

使用以下方法创建绘图:

library(lattice)
xyplot(X8+X9+X10~X1,H,type=c('p','l','g'),
col = c('yellow', 'green', 'blue','red'),
ylab='Count',layout=c(3, 1), 
xlab=paste("H",'difference',min(pmin(H$perc, na.rm = TRUE),na.rm=TRUE),
'% change count'))

我试图让代码显示 "diff" 列的相应差异值和 X2 列的值,以及最低差异(这是 min 函数正在做的) .我试过使用 "match" 是徒劳的。有人可以帮忙吗?

也许你可以试试

ind <- which.min(H$perc)
label1 <- paste0("H difference ", H$diff[ind], "% change count")
label2 <- paste('X2 value', H$X2[ind])
xyplot(X8+X9+X10~X1,H,type=c('p','l','g'),
col = c('yellow', 'green', 'blue','red'),
ylab='Count',layout=c(3, 1), 
xlab=paste(label1, label2, sep=", "))

更新

如果您有多个数据集,请创建一个函数

labelfn <- function(dat, Col1, Col2, diffCol){
  args <- as.list(match.call())[-1]
  e1 <- eval(args$Col1, dat)
  e2 <- eval(args$Col2, dat)
  e3 <- eval(args$diffCol, dat)
  ind <- which.min(e1)
  label1 <- paste0(deparse(args[[1]]), ' difference ', 
           e3[ind], '% change count')
  label2 <- paste(deparse(args[[3]]), ' value', e2[ind])
  paste(label1, label2, sep=", ")
 }

 labelfn(G, perc, X2, diff)
 #[1] "G difference -14% change count, X2  value 5"
  labelfn(H, perc, X2, diff)
 #[1] "H difference -2% change count, X2  value 18"