首页 > 解决方案 > 为什么“逻辑”参数为向量和小标题返回不同的输出

问题描述

有人能告诉我为什么“逻辑”参数为向量和小标题返回不同的输出:

 a<-c(1,0,"t")
 the_numeric<-vector("logical",length(a))
 for (i in seq_along(a)) the_numeric[[i]] <- is.numeric(a[[i]])
 the_numeric
[1] FALSE FALSE FALSE

 df<-tibble::tibble(
     a=rnorm(10),
     b=rnorm(10),
     c=sample(letters,10)
     )
 the_numeric<-vector("logical",length(df))
 for (i in seq_along(df)) the_numeric[[i]] <- is.numeric(df[[i]])
 the_numeric
[1]  TRUE  TRUE FALSE

标签: rtibble

解决方案


区别不在于向量与小标题之间,而是向量与列表之间的区别(小标题/数据框是一种特殊的列表)。

向量只能保存一类数据。因此,a成为字符的所有值是最常见的类,但数据框/小标题并非如此,它们可以在不同的列中保存不同类的数据。

a<- c(1,0,"t")
a
#[1] "1" "0" "t"

class(a)
#[1] "character"

sapply(df, class)
#          a           b           c 
#  "numeric"   "numeric" "character" 

推荐阅读