1

我有三个文本文件。我想做一些如下所示的计算并绘制结果。所有文本文件都包含 14 列 X1 到 X14 和 601 行。该代码基本上从所有三个文件中读取 X3 并进行一些计算,然后返回结果。

   ref= read.table("D:\\ref.txt", sep="",header=TRUE)# read first file
   sour1 = read.table("D:\\sour1.txt", sep="",header=TRUE)# read second file
   sour2= read.table("D:\\sour2.txt", sep="",header=TRUE,na.rm=TRUE)# read third file
  result1 = (mean(ref$X3) - ((sd(ref$X3)/sd(sour1$X3))*mean(sour1$X3))+ ((sd(ref$X3)/sd(sour1$X3)*sour1$X3))) # calculate using ref and sour1
result2 = ((mean(ref$X3) - ((sd(ref$X3)/sd(sour2$X3,na.rm=TRUE))*mean(sour2$X3,na.rm=TRUE))+((sd(ref$X3)/sd(sour2$X3,na.rm=TRUE)*sour2$X3))))  # calculate using ref and sour2
plot(ref$X3,result1,ylab="Weight in pounds",xlab="Weight in pounds",col=2)
points(ref$X3,ref$X3, col = 'green')
points(ref$X3,result2, col = 'blue') # from this I get one plot showing 3 variables on y axis against one on x axis.

这只是使用所有数据中的 X3 绘制的图,但我仍然有其他列 X1 到 X14 我的问题是如何对所有其他列执行相同的操作,最终将获得 14 个图。

4

2 回答 2

2

要从1 到 14,您必须使用函数和在列表中Xi获取元素的替代方法:而不是ipasteref[["X3"]]ref$X3

它给出了你的例子:

for (i in 1:14){
        name <- paste('X',i,sep='')
        result1 = (mean(ref[[name]]) - ((sd(ref[[name]])/sd(sour1[[name]]))*mean(sour1[[name]]))+ ((sd(ref[[name]])/sd(sour1[[name]])*sour1[[name]]))) # calculate using ref and sour1
        result2 = ((mean(ref[[name]]) - ((sd(ref[[name]])/sd(sour2[[name]],na.rm=TRUE))*mean(sour2[[name]],na.rm=TRUE))+((sd(ref[[name]])/sd(sour2[[name]],na.rm=TRUE)*sour2[[name]]))))  # calculate using ref and sour2
        plot(ref[[name]],result1,ylab="Weight in pounds",xlab="Weight in pounds",col=2)
        points(ref[[name]],ref$X1, col = 'green')
        points(ref[[name]],result2, col = 'blue')
}
于 2013-03-13T11:46:31.327 回答
2

正如 Pop 所提到的,您需要创建一个列名列表并遍历它们。

lapplyfor为循环提供了一种更优雅的替代方案。

通过更清楚地布置代码,您可以看到在分配result1和的行中有一些奇怪的双括号result2。为了清楚起见,考虑将这些行分解为更小的计算。

columns <- paste0("X", 1:14)
lapply(
  columns,
  function(column)
  {
    result1 <- (
      mean(ref[[column]]) - 
      ((sd(ref[[column]]) / sd(sour1[[column]])) * mean(sour1[[column]])) + 
      ((sd(ref[[column]]) / sd(sour1[[column]]) * sour1[[column]]))
    )   # calculate using ref and sour1
    result2 <- ((  
      mean(ref[[column]]) - 
      ((sd(ref[[column]]) / sd(sour2[[column]], na.rm=TRUE)) * mean(sour2[[column]], na.rm=TRUE)) + 
      ((sd(ref[[column]]) / sd(sour2[[column]], na.rm=TRUE) * sour2[[column]])) 
    ))  # calculate using ref and sour2
    plot(
      ref[[column]],
      result1,
      ylab = "Weight in pounds",
      xlab = "Weight in pounds",
      col  = 2
    )
    points(ref[[column]], ref[[column]], col = 'green')
    points(ref[[column]], result2, col = 'blue') 
  }
)
于 2013-03-13T11:59:38.740 回答