【问题标题】:What is the reason of the error: non-numeric argument to binary operator in R错误的原因是什么:R中二元运算符的非数字参数
【发布时间】:2014-11-14 16:45:36
【问题描述】:

我正在尝试根据异常数据 (+/-) 制作带有单独列的分组(按年份)条形图。 我在 R 中使用了以下脚本和数据。

mydata <- read.csv("F:/MOD13A1_NDVI_500/Mod_ndvi_500_excel/ndvi_anomaly.csv", head=TRUE)
mydata

        NZ       X2000  X2001  X2002  X2003  X2004  X2005  X2006  X2007  X2008
1 High_mountain  0.007 -0.003 -0.002 -0.016  0.011  0.016 -0.007  0.000 -0.003
2         Taiga -0.002  0.018 -0.006 -0.022  0.018  0.004 -0.016  0.025  0.003
3 Forest_steppe  0.004  0.011 -0.044 -0.008  0.009  0.003 -0.004 -0.005 -0.001
4        Steppe  0.001 -0.016 -0.002  0.007 -0.022 -0.004 -0.017 -0.053  0.000

par(xpd=T, mar=par()$mar+c(0,0,0,6))
barplot(as.matrix(mydata[1:6,]), beside=T)

返回错误:

Error in -0.01 * height : non-numeric argument to binary operator

出现这种错误的原因是什么?我在这个站点中发现了几个与二元运算符的错误非数字参数有关的问题,但每种情况都不同。我认为这可能是负(-)值。如何避免这个错误?

【问题讨论】:

  • 不要显示您如何从本地文件中读取mydata,而是提供带有dput(mydata) 输出的数据。

标签: r error-handling plot


【解决方案1】:

它与负值无关。您在将所有内容转换为字符的矩阵中混合了数字和字符类型。观察

as.matrix(mydata[,1:6])
#   NZ              X2000    X2001    X2002    X2003    X2004   
# 1 "High_mountain" " 0.007" "-0.003" "-0.002" "-0.016" " 0.011"
# 2 "Taiga"         "-0.002" " 0.018" "-0.006" "-0.022" " 0.018"
# 3 "Forest_steppe" " 0.004" " 0.011" "-0.044" "-0.008" " 0.009"
# 4 "Steppe"        " 0.001" "-0.016" "-0.002" " 0.007" "-0.022"

你不能真的用很多字符值来制作barplot。尝试省略名称

barplot(as.matrix(mydata[,2:6]), beside=T)

得到

这是假设您的 mydata 最终看起来像

mydata<-structure(list(NZ = structure(c(2L, 4L, 1L, 3L), .Label = c("Forest_steppe", 
"High_mountain", "Steppe", "Taiga"), class = "factor"), X2000 = c(0.007, 
-0.002, 0.004, 0.001), X2001 = c(-0.003, 0.018, 0.011, -0.016
), X2002 = c(-0.002, -0.006, -0.044, -0.002), X2003 = c(-0.016, 
-0.022, -0.008, 0.007), X2004 = c(0.011, 0.018, 0.009, -0.022
), X2005 = c(0.016, 0.004, 0.003, -0.004), X2006 = c(-0.007, 
-0.016, -0.004, -0.017), X2007 = c(0, 0.025, -0.005, -0.053), 
    X2008 = c(-0.003, 0.003, -0.001, 0)), .Names = c("NZ", "X2000", 
"X2001", "X2002", "X2003", "X2004", "X2005", "X2006", "X2007", 
"X2008"), class = "data.frame", row.names = c("1", "2", "3", 
"4"))

【讨论】:

  • 谢谢,这正是我想要的。
猜你喜欢
  • 2016-11-15
  • 1970-01-01
  • 2019-05-03
  • 2016-11-14
  • 2021-08-18
  • 2021-03-24
  • 1970-01-01
  • 2021-03-24
相关资源
最近更新 更多