转置数据帧后 R 变量类型发生变化

标签 r data-structures transpose variable-types

我一直对R中的变量类型感到困惑。现在我在转置数据框后遇到了问题。

例如,我正在使用 table()获取特定向量中每个因子的计数:

data(iris)

count <- as.data.frame(table(iris$Species))
typeof(count$Var1)
# [1] "integer"

typeof(count$Freq)
# [1] "integer"

我的第一个问题是,为什么 count$Var1 是“整数”?字符串也可以是“整数”吗?但这并不重要,因为我可以通过 count$Var1 <- as.character(count$Var1) 更改类型, 然后 typeof(count$Var1)变成“字符”。

现在我用 transposed_count <- as.data.frame(t(count)) 转置这个数据框.但我感到困惑,因为:

typeof(transposed_count[1,])
[1] "list"

typeof(transposed_count[2,])
[1] "list"

transposed_count[2,]
     V1 V2 V3
Freq 50 50 50

为了后续使用,我需要 transposed_count[2,]成为一个数字向量,如:

transposed_count[2,]
[1] 50 50 50

我该怎么做?为什么他们在t()之后变成了“列表”? ?对不起,如果这是一个愚蠢的问题。谢谢!

最佳答案

My 1st question would be, why is count$Var1 "integer"?

因为因子是整数存储类型

> is.factor(count$Var1)
[1] TRUE

和虹膜 data.frame 中的“字符串”(在 R 中很典型)被存储为因子。

And why did them become "list" after t()?

当您转置时,您会得到一个矩阵,并且矩阵的每个条目都必须具有相同的存储类。您实际上首先得到的是一个字符矩阵,因为整数值将被强制转换。然后,当您随后更改为 data.frame 时,默认情况下这些字符将被强制转换为(新)因子。

> t(count)
     [,1]     [,2]         [,3]       
Var1 "setosa" "versicolor" "virginica"
Freq "50"     "50"         "50" 

> transposed_count <- as.data.frame(t(count))

> transposed_count[2,1]
Freq 
  50 
Levels: 50 setosa
> as.numeric(transposed_count[2,1])
[1] 1

那么现在计数为 50 的是一个数值为 1 的因子!不是你想要的。

至于为什么typeof(transposed_count[1,])是一个列表?作为 data.frame 的水平切片,它实际上是一个 data.frame。

> is.data.frame(transposed_count[2,])
[1] TRUE

而 data.frames 只是带有类信息的列表。

But how can I get a "transposed" data frame then?

听起来你可能想要

> library(reshape2)
> dcast(melt(count), variable~Var1)
Using Var1 as id variables
  variable setosa versicolor virginica
1     Freq     50         50        50

after I read all samples in, I'm gonna rbind all data frame

您必须确保列正确排列。根据即将进行的分析,rbind 可能更自然,因为它与指示来源的另一列一样。

> count2 <- count
> count$source = "file1"
> count2$source = "file2"
> (mcount <- rbind(count,count2))
        Var1 Freq source
1     setosa   50  file1
2 versicolor   50  file1
3  virginica   50  file1
4     setosa   50  file2
5 versicolor   50  file2
6  virginica   50  file2

现在,如果您确实想稍后 reshape ,则不必担心对齐问题

> dcast(melt(mcount), ...~Var1)
Using Var1, source as id variables
  source variable setosa versicolor virginica
1  file1     Freq     50         50        50
2  file2     Freq     50         50        50

关于转置数据帧后 R 变量类型发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42258732/

相关文章:

r - r 中同时点位置之间的距离

r - Slidify:代码对齐

r - 冲积图中组之间的不对称距离

r - 来自 R 中 Erlang 分布的样本

c++ - 如何水平打印二叉树?

java - 如何在二叉搜索树的查找操作中使用 return 关键字

Java 从提供的索引检索列表有效负载

SQL Server 如何在没有 PIVOT 或 UNPIVOT 或聚合的情况下将行转置为列

Python - 使用 numpy 转置列表(不同长度的行)失败

awk - 内存高效转置 - Awk