【问题标题】:Print elements of vector in single line在单行中打印向量的元素
【发布时间】:2021-01-12 09:18:28
【问题描述】:

我有一个包含 12 行和两列的数据框,其中一列带有日期,另一列带有温度。 我想在我的 if 语句中提取符合标准的值(温度小于或等于 -20)。这是我的代码:

for (row in 1:12) {
  T <- winter[row, 2]
  
  if(T <= -20) {
    x <-c(winter[row,2])
    print(x)
  }
}

Print x 给了我这个:

[1] -27
[1] -21
[1] -24
[1] -34
[1] -20

但我想要这样的东西:

[1] -27, -21, -24, -34, -20

输入:

dput(winter)
structure(list(date = 1:12, temp = c(-27L, -21L, -8L, -12L, 
-10L, -24L, 8L, -7L, -34L, -19L, -2L, -20L)), class = "data.frame", row.names = c(NA, 
-12L))

【问题讨论】:

  • 不要使用print 来生成输出。相反,将结果保存到对象中。 (另外,我建议不要使用T 作为变量名,因为它是TRUE 的简写。)
  • @Axeman 如何保存到对象?

标签: r dataframe for-loop if-statement vector


【解决方案1】:

利用向量化条件索引(基本上只是找出你想要的行):

mask <- winter[1:12, 2] <= -20

winter[mask, "temp"]
# [1] -27 -21 -24 -34 -20

这有时被称为“布尔掩码”,尽管这是 Python 中更常见的术语。您可以在 Hadley 的“Advanced R”一书here 的第 4.5.7 节中阅读 R 中的这种索引方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多