循环使用未命名的列以在R

时间:2016-11-15 03:41:44

标签: r sapply

我有以下未命名列的数据框。

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")

我希望在同一个图表上将每两列绘制在一起。我的数据输出是第一列是&#34; x&#34;变量和后面的列是&#34; y&#34;变量。 例如,第1列,第2列是x,y坐标 第3列,第4列是另一个x,y坐标。

我能够绘制第一列,但后来在尝试在各种未命名的列中应用函数时遇到了困难。

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= ".")

我知道不建议使用循环,所以我感觉有趣的是循环遍历列的长度。 谢谢!

2 个答案:

答案 0 :(得分:3)

LocalDateTime date = LocalDateTime.now();
appointmentViewWeeks view = new appointmentViewWeeks(String.valueOf(date.getYear()),
                                                        String.valueOf(date.getMonth()));

答案 1 :(得分:1)

使用ggplot:

library(ggplot2)
df <- do.call(rbind, lapply(seq(1,ncol(test_df), by=2), 
      function(x) data.frame(x=test_df[,x], y=test_df[,x+1], plot=as.factor((x+1)/2))))
ggplot(df, aes(x,y, group=plot, col=plot)) + geom_line(lwd=1.5)

enter image description here