【问题标题】:Why does R output 2 and not 8 here?为什么R在这里输出2而不是8?
【发布时间】:2021-11-03 14:05:10
【问题描述】:

我创建一个数据框并选择值高于 x 的子集。但是当 x = 50 时,r 输出 2 而不是 8:

input <- readLines('stdin')
x <- as.integer(input[1])

data <- data.frame(
"id" = c(1:10),
"grade" = c(75, 26, 54, 90, 86, 93, 
48, 71, 66, 99)
)

hscores <- subset(data,grade>x)
print(length(hscores))

【问题讨论】:

  • subset(data,grade&gt;50) 为我返回 8 行。但是length(hscores) 不返回行数,而是返回列数。我想你正在寻找print(nrow(hscores))
  • 避免从剪贴板读入 b/c 容易出错且不可重现。为什么不能给 x 赋值 50?
  • 是的,谢谢马丁,我现在明白了。另外,感谢 Eyayaw,注意到了。
  • 请修剪您的代码,以便更容易找到您的问题。请按照以下指南创建minimal reproducible example

标签: r subset


【解决方案1】:

我们也可以这样做

library(dplyr)
hscores %>%
   summarise(n = n()) %>%
   pull(n)

【讨论】:

    【解决方案2】:

    length 在数据帧上使用时返回数据帧中的列数,在这种情况下为 2。要计算行数,您可以使用nrowNROW。您还可以将向量传递给length

    nrow(hscores)
    #[1] 8
    
    NROW(hscores)
    #[1] 8
    
    length(hscores$id)
    #[1] 8
    

    【讨论】:

      猜你喜欢
      • 2021-03-21
      • 2015-12-20
      • 2020-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多