tl; dr - R中的矢量到底是什么?
长版:
很多东西是R中的向量.例如,数字是长度为1的数字向量:
is.vector(1)
[1] TRUE
Run Code Online (Sandbox Code Playgroud)
列表也是一个向量.
is.vector(list(1))
[1] TRUE
Run Code Online (Sandbox Code Playgroud)
好的,所以列表是一个向量.显然,数据框是一个列表.
is.list(data.frame(x=1))
[1] TRUE
Run Code Online (Sandbox Code Playgroud)
但是,(似乎违反了传递属性),数据帧不是矢量,即使数据帧是列表,列表也是矢量.编辑:它是一个向量,它只有其他属性,这会导致这种行为.见下面接受的答案.
is.vector(data.frame(x=1))
[1] FALSE
Run Code Online (Sandbox Code Playgroud)
为了以另一种方式回答你的问题, R Internals手册列出了R的八种内置矢量类型:"逻辑","数字","字符","列表","复杂","原始","整数"和"表达".
要测试一个对象的非属性部分是否真的是"在它下面"的那些矢量类型之一,你可以检查结果is(),如下所示:
isVector <- function(X) "vector" %in% is(X)
df <- data.frame(a=1:4)
isVector(df)
# [1] TRUE
# Use isVector() to examine a number of other vector and non-vector objects
la <- structure(list(1:4), mycomment="nothing")
chr <- "word" ## STRSXP
lst <- list(1:4) ## VECSXP
exp <- expression(rnorm(99)) ## EXPRSXP
rw <- raw(44) ## RAWSXP
nm <- as.name("x") ## LANGSXP
pl <- pairlist(b=5:8) ## LISTSXP
sapply(list(df, la, chr, lst, exp, rw, nm, pl), isVector)
# [1] TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE
Run Code Online (Sandbox Code Playgroud)
说明@joran指出的,is.vector在具有除名称之外的任何属性的向量上返回 false (我从来不知道)......
# 1) Example of when a vector stops being a vector...
> dubious = 7:11
> attributes(dubious)
NULL
> is.vector(dubious)
[1] TRUE
#now assign some additional attributes
> attributes(dubious) <- list(a = 1:5)
> attributes(dubious)
$a
[1] 1 2 3 4 5
> is.vector(dubious)
[1] FALSE
# 2) Example of how to strip a dataframe of attributes so it looks like a true vector ...
> df = data.frame()
> attributes(df)
$names
character(0)
$row.names
integer(0)
$class
[1] "data.frame"
> attributes(df)[['row.names']] <- NULL
> attributes(df)[['class']] <- NULL
> attributes(df)
$names
character(0)
> is.vector(df)
[1] TRUE
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
629 次 |
| 最近记录: |