【问题标题】:I keep getting a syntax error in my for loop?我的 for 循环中不断出现语法错误?
【发布时间】:2021-09-22 23:05:13
【问题描述】:

我不确定这个循环的子集有什么问题,但我不断收到语法错误:

for (i in 1:length(wc_comp$Section)) {
  print(ggplot(data = (subset(wc_comp, Section == [i]))) +
          geom_jitter(aes(x = Headline, y = Word.Count, color=cols), size=5, width = 0.05) +
          stat_summary(aes(x = Headline, y = Word.Count, group = Article[i]),
                       fun = median, fun.min = median, fun.max = median,
                       geom = "crossbar", color = "black", width = 0.7, lwd = 0.2) +
          ylim(min(wc_comp$Word.Count), max(wc_comp$Word.Count)) +
          xlab("Story") +
          ylab ("Word Count") +
          ggtitle([i]) +
          theme(plot.title=element_text(hjust=0.5, face = "bold", size = 10),
                text = element_text(family = "System Font"),axis.text.x = element_text(size=6)) +
          scale_x_discrete(labels = function(x) str_wrap(x, width = 10)))
}

【问题讨论】:

  • 请包括错误本身,有太多无法猜测。
  • 有几件事跳出来,虽然:(1)[i]不是有效的R代码,使用i来引用i的值; (2) i 在这种情况下总是一个整数,尝试将Sectioni 进行比较是一个逻辑错误。如果你得到一个匹配,我有 99% 的把握这是一个糟糕的匹配。也许你的意思是Section == Section[i]? (3) 我已经完成了理论化,没有样本数据我不想提出假设的修正。

标签: r for-loop syntax


【解决方案1】:

您在两个地方使用语法[i] 来引用循环变量i,这会导致语法错误。删除第 2 行和第 10 行的 [ ] 解决了该问题:

for (i in 1:length(wc_comp$Section)) {
  print(ggplot(data = (subset(wc_comp, Section == i))) +
          geom_jitter(aes(x = Headline, y = Word.Count, color=cols), size=5, width = 0.05) +
          stat_summary(aes(x = Headline, y = Word.Count, group = Article[i]),
                       fun = median, fun.min = median, fun.max = median,
                       geom = "crossbar", color = "black", width = 0.7, lwd = 0.2) +
          ylim(min(wc_comp$Word.Count), max(wc_comp$Word.Count)) +
          xlab("Story") +
          ylab ("Word Count") +
          ggtitle(i) +
          theme(plot.title=element_text(hjust=0.5, face = "bold", size = 10),
                text = element_text(family = "System Font"),axis.text.x = element_text(size=6)) +
          scale_x_discrete(labels = function(x) str_wrap(x, width = 10)))
}

【讨论】:

  • 这是一个很好的答案,但要意识到Section == i 是一个逻辑错误,即使它不是语法错误。想象一下for (i in 1:length(mtcars$disp)) mtcars[mtcars$disp == i,] ...永远不会匹配。
  • 公平点,但也要考虑到我们不知道wc_comp$Section 的值。如果条件wc_comp$Section[n] == n成立,那么我认为逻辑错误消失了。
  • 只有当wc_comp$Sectioninteger 类,并且在其长度上从1 完全增加1 时,它才会起作用。如果有任何不同,则 OP 的代码在逻辑上是不一致的。但是,如果相同,我认为这段代码仍然很脆弱,很容易误入歧途。一个使用for (i in 1:length(.)) 迭代indices(无论如何这很糟糕,应该使用seq_len),或者一个使用for (i in wc_comp$Section) 迭代values。如果它们碰巧有一次,恭喜,它仍然很糟糕而且很脆弱。
猜你喜欢
  • 2014-01-23
  • 1970-01-01
  • 2017-07-08
  • 1970-01-01
  • 2015-04-17
  • 2015-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多