如何在没有循环的Base R中创建包含组的线图?

Max*_*x C 12 r

我需要使用以下数据创建一个包含组的简单线图:

test = data.frame(x =  rep(1:3, each = 2),
                  group =  rep(c("Group 1","Group 2"),3),
                  groupcd= rep(c(1,2),3),
                  y=   c(22,8,11,4,7,5)
                  )
Run Code Online (Sandbox Code Playgroud)

我可以用GGPLOT轻松完成:

library(ggplot2)
    #GGPLOT
    qplot(x=x, y=y, 
           data=test, 
           colour=group, 
           main="GGPLOT line plot with groups") +
      geom_line()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我也可以用TRELLIS做到:

library(lattice)
xyplot(y~x,
       type="b",
       group=group,
       data=test,
       main="TRELLIS line plot with groups",
       auto.key =list(
         lines = TRUE)
       )
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

但是,我现在有点不愿意使用GGPLOT或TRELLIS.我希望能够用Base R创建这个图.我可以让这个图在Base R中工作的唯一方法是使用for循环:

# set up empty plot
plot(test$y ~test$x,  ylab="y", xlab="x", type="n", main="Base R line plot with groups")
colors<-c("red","blue")
#plot each group in the for loop
number_of_groups <- as.numeric(max(unique(test$groupcd))) #calculate number of groups
for (i in 1:number_of_groups) 
{
  temp <- subset(test,  groupcd==i )
  lines(temp$x, temp$y, col=colors[i])  
  points(temp$x, temp$y, col=colors[i])  
}
legend("top", legend=unique(test$group), text.col =colors  )
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

这种方法似乎很复杂.在基地R有更简单的方法吗?基础R绘图功能中是否有组选项?非常感谢.

the*_*ail 8

这样的事情可以作为工作的基础:

test = data.frame(x =  rep(1:3, each = 2),
                  group =  rep(c("Group 1","Group 2"),3),
                  groupcd= rep(c(1,2),3),
                  y=   c(22,8,11,4,7,5)
                  )

xvals <- split(test$x,test$group)
yvals <- split(test$y,test$group)

plot(1:max(unlist(xvals)),ylim=(c(0,max(unlist(yvals)))),type="n")
# thanks to @BenBolker for refining this next key line
mapply(lines,xvals,yvals,col=c("red","blue"),pch=1:2,type="o")
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述