如何在循环中给公式值

How to give a formula values in a loop

我有一个程序应该在给定 activity 的 csv 和时间的情况下创建活动图的 pdf 文件。我需要遍历多个 activity 列,每个主题一个。第一个activity列是第3列,这里是相关代码:

pdf("All Actograms.pdf")
for(i in 3:(length(dat) - 1)) {
  activity <- colnames(dat)[i]

  # Plot the actogram
  print(actogram(activity~datetime, dat=dat, col="black", main=colnames(dat)[i], strip.left.format="%m/%d", doublePlot = TRUE, scale=0.75))
}
dev.off()

当我调用我的 actogram 函数时,出现错误 "non-numeric argument to binary operator." 问题出在公式 "activity~datetime," 上,因为 datetime 是一个列名,activity 也应该是。如果我在循环之外尝试它,使用 activity 列的名称而不是包含该名称的变量,它工作正常。调试后,我发现 actogram 函数正在接收字符串 "activity," 而不是变量 activity。我不太了解公式,但我想知道是否有任何方法可以完成我正在尝试做的事情,即循环遍历许多列,每次调用 actogram 函数时更改“~”之前的列。我是 R 的新手。

谢谢!

我们没有您正在处理的数据,但我认为您可以做的最简单的事情如下:

pdf("All Actograms.pdf")
for(i in 3:(length(dat) - 1)) {

  activity <- colnames(dat)[i]#save the name of the column I  
  colnames(dat)[i] <- "activity" # change the name of column I to activity
   # Plot the actogram
  print(actogram(activity~datetime, dat=dat, col="black", main=activity, strip.left.format="%m/%d", doublePlot = TRUE, scale=0.75))

   colnames(dat)[i] <- activity # change back the name of the column I to its original name
 }
dev.off()

希望它有效。