R:正确/错误结果不正确

时间:2018-10-04 13:03:49

标签: r sum

目前我还没有添加数据样本,因为这似乎无关紧要...

我要表演:

sum(df$y[df$x4 %in% c("1.A", "1.B", "1.C", "1.D") & x == "1990" & x2 == 
"Austria" & x1!="All greenhouse gases - (CO2 equivalent)"])
==sum(df$y[df$x4 in% c("1") & df$x == "1990" & df$x2 == "Austria" & x1!="All 
greenhouse gases - (CO2 equivalent)"])

预期结果:“ TRUE”

表演时

sum(df$y[df$x4 %in% c("1.A", "1.B", "1.C", "1.D") & x == "1990" & x2 == 
"Austria" & x1!="All greenhouse gases - (CO2 equivalent)"])

我得到[1] 51347.52

执行第二次操作时,我得到相同的结果。

sum(df$y[df$x4 in% c("1") & df$x == "1990" & df$x2 == "Austria" & x1!="All 
greenhouse gases - (CO2 equivalent)"])

到目前为止很好。

但是,执行本文开头所述的操作时,我得到“ FALSE”,这是通过分别运行两个操作进行测试所得出的结论。怎么会这样?

数据源有五个小数位,但这真的是由于这个原因吗?

在任何情况下都谢谢......

1 个答案:

答案 0 :(得分:0)

编辑:这应该可行

构建数据框

df <- data.frame(x = 1990, 
                 x2 = "Austria", 
                 x4 = c("1.A", "1.B", "1.C", "1.D", "1.E", 
                        "1.F", "1.G", "1.H", "1.I", "1.J"), 
                 y = c(0.000000000001:0.000000000010), 
                 x1 = "Yearly gases")

df
      x      x2  x4     y           x1
1  1990 Austria 1.A 1e-12 Yearly gases
2  1990 Austria 1.B 1e-12 Yearly gases
3  1990 Austria 1.C 1e-12 Yearly gases
4  1990 Austria 1.D 1e-12 Yearly gases
5  1990 Austria 1.E 1e-12 Yearly gases
6  1990 Austria 1.F 1e-12 Yearly gases
7  1990 Austria 1.G 1e-12 Yearly gases
8  1990 Austria 1.H 1e-12 Yearly gases
9  1990 Austria 1.I 1e-12 Yearly gases
10 1990 Austria 1.J 1e-12 Yearly gases

求和结果

# Formula 1
sum(df$y[df$x4 %in% c("1.A", "1.B", "1.C", "1.D") &
             df$x == "1990" &
             df$x2 == "Austria" &
             df$x1 != "All greenhouse gases - (CO2 equivalent)"]) 
[1] 4e-12


# Formula 2
sum(df$y[df$x4 %in% c("1") &
             df$x == "1990" &
             df$x2 == "Austria" &
             df$x1 != "All greenhouse gases - (CO2 equivalent)"])
[1] 0

结果==

sum(df$y[df$x4 %in% c("1.A", "1.B", "1.C", "1.D") &
             df$x == "1990" &
             df$x2 == "Austria" &
             df$x1 != "All greenhouse gases - (CO2 equivalent)"]) ==
sum(df$y[df$x4 %in% c("1") &
             df$x == "1990" &
             df$x2 == "Austria" &
             df$x1 != "All greenhouse gases - (CO2 equivalent)"])
[1] FALSE

结果为all.equal

isTRUE(all.equal(sum(df$y[df$x4 %in% c("1.A", "1.B", "1.C", "1.D") &
                              df$x == "1990" &
                              df$x2 == "Austria" &
                              df$x1 != "All greenhouse gases - (CO2 equivalent)"]),
                 sum(df$y[df$x4 %in% c("1") &
                              df$x == "1990" &
                              df$x2 == "Austria" & 
                              df$x1 != "All greenhouse gases - (CO2 equivalent)"]))
       )
[1] TRUE