"NAs introduced by coercion",将因子转换为数字



任务:总结列中的所有元素。

问题:这样做时,以下错误出现了"强制引入的NA"。

我如何避免这种情况?这是我到目前为止所做的:

load dataset and get the table:
dat <- read.table("http://stat.ethz.ch/Teaching/Datasets/milben.dat")            
get the first column and exclude first element: 
fc<- dat[-1,1]         
transform factors in numbers and compute the sum
sum(as.numeric(levels(fc))[fc]) numbers

非常感谢!

从我收集的内容中,您似乎要总结频列。以下代码(使用Tidyverse)可能会有所帮助:

library(tidyverse)

df <- read_table('http://stat.ethz.ch/Teaching/Datasets/milben.dat')
df %>%
  summarize(
    total = sum(frequency)
  )

输出为:

# A tibble: 1 x 1
  total
  <dbl>
1   150

这是一个简单的data.table解决方案。@www评论最好。然后,您使用sum(fc$n)和/或sum(fc$frequency)

library(data.table)
library(magrittr)
dat <- fread("http://stat.ethz.ch/Teaching/Datasets/milben.dat") %>% 
  .[-1]
dat[, lapply(.SD,
             sum)]
#>     n frequency
#> 1: 28        80

由Reprex软件包(V0.2.1)在2019-02-28创建

最新更新