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

R variable types changes after transposing data frame

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

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

data(iris)

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

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

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

现在我将这个数据框转置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()之后变成了"list"?对不起,如果这是一个愚蠢的问题。谢谢!

typeof 将告诉您 R 如何在内部存储数据。对于因子,这是整数。 Var1 是一个因素,看到了吗?

> class(count$Var1)
[1] "factor"

transposed_counts 在这种情况下没有任何意义。通过转置你破坏了 data.frame 逻辑。转置通常对矩阵有意义。如果你想 "reflow" 一个 data.frame,你可以使用像 reshape 或它的任何亲戚。

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

因为因子是整数存储类型

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

和虹膜 data.frame 中的 "strings",在 R 中是典型的,被存储为因子。

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

当您转置时,您会得到一个矩阵,并且矩阵的每个条目必须具有相同的存储 class。您实际上首先得到的是一个字符矩阵,因为整数值将被强制转换。然后,当您随后更改为 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.frame 只是包含 class 信息的列表。

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

现在,如果您以后想重塑形状,就不必担心对齐问题

> 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

如果在转置之前将 Var1 中的物种名称设为行名,则可以避免将所有内容转换为相同数据类型的转置问题。

data(iris)
count <- as.data.frame(table(iris$Species))
row.names(count) <- count$Var1
count$Var1 <- NULL
transposed_count <- as.data.frame(t(count))
as.numeric(transposed_count[1,])
# [1] 50 50 50