knit to html不会执行第70行错误的b/c?

Knit to html will not execute b/c of error in line 70?

我正在尝试创建一个函数,用于计算数值向量的观测值与向量平均值之间的差异,并将其应用于 NHANES 数据框。这是给出错误的可疑代码:

library(NHANES)

deviation <- function(x)
  {sd(x) - mean(x)}


sapply(NHANES[1:6,], deviation)

这是错误:

Quitting from lines 70-82  
Error in var(if (is.vector(x) || is.factor(x)) x else as.double(x), na.rm = na.rm) : 
  Calling var(x) on a factor x is defunct.
  Use something like 'all(duplicated(x)[-1L])' to test for a constant vector.
Calls: <Anonymous> ... eval -> eval -> sapply -> lapply -> FUN -> sd -> var
Execution halted

有人知道会发生什么吗?

NHANES的列中有不能应用算术运算的因子列。就是这个问题。

> str(NHANES[1:6,])
tibble [6 × 76] (S3: tbl_df/tbl/data.frame)
 $ ID              : int [1:6] 51624 51624 51624 51625 51630 51638
 $ SurveyYr        : Factor w/ 2 levels "2009_10","2011_12": 1 1 1 1 1 1
 $ Gender          : Factor w/ 2 levels "female","male": 2 2 2 2 1 2
 $ Age             : int [1:6] 34 34 34 4 49 9
 $ AgeDecade       : Factor w/ 8 levels " 0-9"," 10-19",..: 4 4 4 1 5 1
...

例如,如果您执行 sapply(NHANES[1:6, c(1,4)], deviation),它会起作用,因为您将函数应用于数字(实际上是整数)数据(IDAge