为 pre-post 数据集创建 xyplot

Creating an xyplot for pre-post dataset

我正在尝试根据我的数据集的以下示例创建一个 xyplot:

dput(head(trainsamp,25))
structure(list(group = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 
3L, 3L), .Label = c("Endurance", "Strength", "Concurrent"), class = "factor"), 
time = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L
), .Label = c("Pre", "Post"), class = "factor"), FFM = c(55.883166, 
56.658898, 57.933614, 65.295368, 63.199246, 65.906551, 51.201461, 
49.218984, 53.773112, 71.202309, 53.042409, 50.749445, 50.771442, 
54.768907, 52.981304, 56.578874, 55.442133, 51.263485, 54.639979, 
60.626251, 59.256806, 63.780228, 67.094356, 55.860919, 59.185318
), id = 1:25), .Names = c("group", "time", "FFM", "id"), row.names = c("1.1", 
"2.1", "3.1", "4.1", "5.1", "6.1", "7.1", "8.1", "9.1", "10.1", 
"11.1", "12.1", "13.1", "14.1", "15.1", "16.1", "17.1", "18.1", 
"19.1", "20.1", "21.1", "22.1", "23.1", "24.1", "25.1"), class = "data.frame")

我试过以下代码:

library(lattice)
xyplot(trainsamp$FFM~trainsamp$time|trainsamp$id,group=trainsamp$group,type="l",col=c("blue","red","black"),
   ylab="Mean Fat Free Mass (kg)",xlab="Time",
   main="Individual Trajectories")
legend(locator(1),legend=levels(group),lty=1,col=c("blue","red","black"))

我继续得到图表,但图例似乎丢失了,我收到以下错误:

Error in levels(group) : object 'group' not found

我想避免使用 attach 命令。谁能告诉我为什么 "group" 有问题?

这是一个迟到的答案,但您的部分问题是 legend() 是基础图形,而 xyplot 来自 lattice,这两者不能很好地混合。您可以只使用 auto.key=T 参数来添加一个键。这是您的代码的稍微清理过的版本:

xyplot(FFM~time | id, group=group, data=trainsamp, type="p",      
   col=c("blue","red","black"),  ylab="Mean Fat Free Mass (kg)",
   xlab="Time",main="Individual Trajectories", auto.key=T)