R-不列出时将其他元素强制转换为字符 [英] R -- coerces other elements to character when unlisted
问题描述
我无法理解R的这种行为.
I am not able to understand this behavior of R.
a <- list("a" = 1, "b" = 2, "c" = NA, "d" = Inf)
vec <- unlist(a, use.names=FALSE)
print(vec)
[1] 1 2 NA Inf
当列表中有一个字符值时,它将所有未列出的值强制转换为字符.为什么要这样做?而且,为什么NA 不强制字符?
When there is a character value in the list it coerces all the unlisted values to character. Why is this done? And, why is NA not coerced to character?
a = list("a" = 1, "b" = 2, "c" = NA, "d" = Inf, "e" = "pass")
vec = unlist(a, use.names=FALSE)
print(vec)
[1] "1" "2" NA "Inf" "pass"
推荐答案
这是列表和向量的属性的简要摘要.可以在这本书中找到更多详细信息.
here is a brief summary of properties of lists and vectors. More details can be found in this book.
广义上讲,R中有两种不同的一维数据结构.
Broadly speaking, there are two different one-dimensional data structures in R.
-
原子向量:原子向量的所有元素都必须具有相同的类型
Atomic vectors: all elements of an atomic vector must be the same type
列表:列表的元素可以具有不同的类型
Lists: the elements of a list can have different types
原子向量的所有元素都必须是相同的类型,因此当您尝试组合不同的类型时,它们将被强制转换为最灵活的类型.从最小到最灵活的类型是:逻辑,整数,双精度和字符.
All elements of an atomic vector must be the same type, so when you attempt to combine different types they will be coerced to the most flexible type. Types from least to most flexible are: logical, integer, double, and character.
例如,将一个字符和一个整数组合会产生一个字符:
For example, combining a character and an integer yields a character:
str(c("a", 1))
如您所见:强制通常会自动发生.
As you see: coercion often happens automatically.
这篇关于R-不列出时将其他元素强制转换为字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!