How to create a line plot with groups in Base R without loops?
r
Solution
What about something like this as a base to work from:
test = data.frame(x = rep(1:3, each = 2),
group = rep(c("Group 1", "Group 2"), 3),
group_cd = 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")
Result:
Problem
I need to create a simple line plot with groups using the following data: ``` 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) ) ``` I can easily do it with GGPLOT: ``` library(ggplot2) #GGPLOT qplot(x=x, y=y, data=test, colour=group, main="GGPLOT line plot with groups") + geom_line() ``` I can also do it with TRELLIS: ``` library(lattice) xyplot(y~x, type="b", group=group, data=test, main="TRELLIS line plot with groups", auto.key =list( lines = TRUE) ) ``` However, I am a bit reluctant to use GGPLOT or TRELLIS right now. I'd like to be able to create this graph with Base R. The only way I can get this plot to work in Base R is by using for loop: ``` # 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 ) ``` This approach seems quite convoluted. Is there an easier way to do it in base R? Is there a group option in base R plot function? Thank you so much.