【问题标题】:R - argument is not numeric or logical: returning NAR - 参数不是数字或逻辑:返回 NA
【发布时间】:2016-02-18 15:25:17
【问题描述】:

我正在尝试获取从 Excel 表中读取的数据的平均值。

library(readxl)
URL <- "C:/Users/user/Documents/R/test.xlsx"
pivot <- read_excel(URL,sheet=2)
pivot
mean(pivot$Experimental)

以下excel中的数据。执行上述代码时,此数据会显示在控制台窗口中。

 Experimental   Comparison
   -0.255      -0.324
   -0.213      -0.185
   -0.190      -0.299
   -0.185      -0.144
   -0.045      -0.027
   -0.025      -0.039
   -0.015      -0.264
    0.003      -0.077
    0.015      -0.017
    0.020      -0.169
    0.023      -0.096
    0.040      -0.330
    0.040      -0.346
    0.050      -0.191
    0.055      -0.128
    0.058      -0.182  

我收到以下警告消息,平均函数的结果为 NA。

Warning message:
In mean.default(pivot$Experimental) :
  argument is not numeric or logical: returning NA

【问题讨论】:

  • 告诉我们str(pivot),即编辑您的问题!
  • 很可能 Experimental 列是 factor 出于某种原因。通过pivot$Experimental&lt;-as.numeric(as.character(pivot$Experimental))强制他们
  • @jogo chr " -0.255" str(pivot) 的结果
  • @nicola 有警告NAs introduced by coercion
  • @Ayubx 为什么你不只是发布dput(pivot) 的输出让我们看看它实际包含什么?每个问题都应该是可重复的,如果您不提供相关信息,您将不会获得任何帮助。

标签: r


【解决方案1】:

@Ayubx @nicola 向您提出的问题是,您如何理解字符的平均值?你不能,所以你需要将字符转换为数字。下面是一个例子。

> d <- c("5","7")
> str(d)
chr [1:2] "5" "7"
> e <- as.numeric(d)
> str(e)
num [1:2] 5 7
> mean(d)
[1] NA
Warning message:
In mean.default(d) : argument is not numeric or logical: returning NA
> mean(e)
[1] 6

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 2020-11-16
    • 2018-08-11
    • 2023-03-02
    • 1970-01-01
    相关资源
    最近更新 更多