如何处理错误“var(x) : 在因子 x 上调用 var(x) 已失效”。在R?

var(x)当我们尝试对因子数据应用数值函数时,会出现错误“调用因子 x 已失效”。

例如,如果我们在数据框中有一个因子列,那么在该列上应用数值函数将导致上述错误。为了解决这个问题,我们可以将as.numeric函数与数值函数一起使用,如下例所示。

示例 1

以下代码段创建了一个示例数据框 -

x<-factor(rpois(20,5))
df<-data.frame(x)
df
输出结果

创建以下数据框 -

    x
1   7
2   3
3   7
4   4
5   7
6   6
7   4
8   6
9   8
10  2
11  6
12  6
13  9
14  5
15  3
16  4
17 10
18  2
19  4
20  2

现在,为了对 x 中的数据应用 t 测试,将以下代码添加到上面的代码片段中 -

t.test(df$x,mu=2)
输出结果

如果您将上述所有给定的片段作为单个程序执行,它会生成以下输出 -

Error in var(x) : Calling var(x) on a factor x is defunct.

因此,使用类似下面的 ' 来测试常量向量。

'all(duplicated(x)[-1L])
输出结果

如果您将上述所有给定的片段作为单个程序执行,它会生成以下输出 -

In addition: Warning message:
In mean.default(x) : argument is not numeric or logical: returning NA

现在,在应用as.numeric函数时在 x 上使用t.test函数并将以下代码添加到上面的代码段中 -

t.test(as.numeric(df$x),mu=2)
输出结果

如果您将上述所有给定的片段作为单个程序执行,它会为一个样本 t-test 生成以下输出 -

data: as.numeric(df$x)
t = 4.3061, df = 19, p-value = 0.0003811
alternative hypothesis: true mean is not equal to 2
95 percent confidence interval:
   3.156355 5.343645
sample estimates:
mean of x
   4.25

示例 2

以下代码段创建了一个示例数据框 -

y<-factor(rpois(20,2))
dat<-data.frame(y)
dat

创建以下数据框 -

    y
1   1
2   2
3   4
4   4
5   2
6   0
7   0
8   1
9   3
10  0
11  2
12  0
13  0
14  2
15  2
16  2
17  2
18  0
19  4
20  2

现在,为了对数据应用 t 测试,将以下代码添加到上面的代码片段中 -

t.test(dat$y,mu=0)
输出结果

如果您将上述所有给定的片段作为单个程序执行,它会生成以下输出 -

Error in var(x) : Calling var(x) on a factor x is defunct.

使用类似以下内容来测试常量向量 -

'all(duplicated(x)[-1L])'
输出结果

如果您将上述所有给定的片段作为单个程序执行,它会生成以下输出 -

In addition: Warning message:
In mean.default(x) : argument is not numeric or logical: returning NA

现在,在应用as.numeric函数时在 y 上使用t.test函数,将以下代码添加到上面的代码段中 -

t.test(as.numeric(dat$y),mu=0)
输出结果

如果您将上述所有给定的片段作为单个程序执行,它会为一个样本 t-test 生成以下输出 -

data: as.numeric(dat$y)
t = 8.5446, df = 19, p-value = 6.216e-08
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
   2.000878 3.299122
sample estimates:
mean of x
   2.65

猜你喜欢