(R) 列表示适用于一个命令但不适用于另一个命令

(R) column mean works with one command but not with another

我已将此数据集(可用 here)作为 csv 文件导入 R:

oxcgrt <- read_csv("C:/Users/Local/Documents/COVID19datasets/OxCGRT/OxCGRT_latest.csv")

Parsed with column specification: cols( .default = col_double(),
CountryName = col_character(), CountryCode = col_character(),
M1_Wildcard = col_logical() ) See spec(...) for full column specifications.

我在变量“E1_Income 支持”上使用了 summarize()

summarize(oxcgrt, inc_sup = mean("E1_Income support", na.rm = TRUE))
# A tibble: 1 x 1
  inc_sup
    <dbl>
1      NA
Warning message:
In mean.default("E1_Income support", na.rm = TRUE) :
  argument is not numeric or logical: returning NA

问题可能不是变量中的 NA 值,因为我指定了“na.rm = TRUE”。然而,另一个命令是这样做的:

mean(oxcgrt$"E1_Income support", na.rm=TRUE)
# [1] 0.4758057

变量“E1_Income support”不是数字:

is.numeric("E1_Income support")
# [1] FALSE

有谁知道为什么后者可以计算平均值而前者不能? 谢谢

P.S.: 数据每天更新,所以变量平均值应该与我报告的平均值略有不同。

您收到该错误是因为您正在写入 "E1_Income support"。在 dplyr 语句中,这被视为一个字符串并且 not 引用数据框的列。为此,您应该删除双引号。

在这种特殊情况下,您实际上需要使用反引号 `` 因为您选择的列名中有一个空格。否则不需要反引号。

summarize(oxcgrt, inc_sup = mean(`E1_Income support`, na.rm = TRUE))
# A tibble: 1 x 1
#   inc_sup
#     <dbl>
# 1   0.477