RCN RCN - 24 days ago 8
R Question

Looping through unnamed columns to plot on one graph in R

I have the following dataframe of unnamed columns.

test_df <- structure(list(V1 = c(738, 734.55, 731.05, 727.48, 723.86, 720.18,
716.45, 712.66, 708.82, 704.91), V2 = c(383, 379.31, 375.69,
372.13, 368.64, 365.22, 361.87, 358.6, 355.37, 352.19), V3 = c(704,
700.8, 697.52, 694.15, 690.71, 687.19, 683.59, 679.92, 676.12,
672.21), V4 = c(316, 312.77, 309.66, 306.66, 303.8, 301.07, 298.49,
296.07, 293.79, 291.63), V5 = c(746, 743.64, 741.15, 738.52,
735.78, 732.93, 729.98, 726.92, 723.69, 720.31), V6 = c(369,
364.63, 360.37, 356.21, 352.15, 348.21, 344.39, 340.68, 337.04,
333.48), V7 = c(715, 711.38, 707.74, 704.06, 700.36, 696.63,
692.87, 689.09, 685.31, 681.51), V8 = c(349, 345.79, 342.62,
339.49, 336.39, 333.33, 330.3, 327.31, 324.26, 321.2)), .Names = c("V1",
"V2", "V3", "V4", "V5", "V6", "V7", "V8"), row.names = c(NA,
10L), class = "data.frame")


I am looking to plot every 2 columns together on the same graph. The output of my data is such that the first column is the "x" variable and the column after is the "y" variable.
For example column 1, column 2 is an x, y coordinate
and column 3, column 4 is another x, y coordinate.

I am able to plot the first column, but then was having difficulties attempting to apply a function across the various unnamed columns.

plot(test_df$V1, test_df$V2, xlab="x", ylab ="y", xlim=c(200, 800), ylim=c(400, 200), main="vowel shapes", col= 'black', pch= ".")
lines(test_df$V1, test_df$V2, xlab="x", ylab ="y", xlim=c(200, 800), ylim=c(400, 200), main="vowel shapes", col= 'black', pch= ".")
lines(test_df$V3, test_df$V4, xlab="x", ylab ="y", xlim=c(200, 800), ylim=c(400, 200), main="vowel shapes", col= 'black', pch= ".")


I know that loops are not advised and so I felt funny looping through the length of the columns.
Thanks!

Answer
matplot(test_df[seq(1,ncol(test_df), by=2)], test_df[seq(2,ncol(test_df), by=2)], t="l", lty=1)