pivot_longer 错误:无法组合不同的类? [英] pivot_longer error: impossible to combine different classes?
问题描述
假设我有这个 df:
df <- data.frame(a= "a", b = 1, col3 = "c", col4 = "d") %>% print()
当我尝试延长"时它使用此代码,
When I try to "lengthen" it using this code,
df %>% pivot_longer(1:4, names_to = "test", values_to = "test2")
我收到以下错误:
Error: Can't combine `a` <factor<127a2>> and `b` <double>.
为什么我会得到这个?因为第一列和第一行都具有相同的值,所以a"是相同的.(我试过 names_repair 参数没有成功)?还是因为 a 和 b 是不同的类?我不明白的是,我经常对不同类的数据进行透视,而且它总是有效.或者,是因为我试图旋转实际的标题(这确实是我需要做的)?
Why do I get this? Because the first column and first row both have the same value, "a" (I've tried names_repair argument without success)? Or because a and b are different classes? What I don't understand is that I often pivot data of different classes and it always works. Or, is it because I am trying to pivot the actual header (this is what I need to do indeed)?
非常感谢任何帮助.期望输出:
Any help much appreciated. Desired output:
#a a
#b 1
#col3 c
#col4 d
推荐答案
这在基础 R 中可能更直接,您可以在其中简单地t
转置数据框.因为它强制转换为矩阵,所以只需转换回 as.data.frame
.
This might be more straightforward in base R, where you may simply t
ranspose the data frame. Because it coerces into a matrix just convert back as.data.frame
.
as.data.frame(t(df))
# V1
# a a
# b 1
# col3 c
# col4 d
使用 unname
来获得更清晰的行名称.
Use unname
to get cleaner row names.
as.data.frame(unname(t(df)))
# V1
# 1 a
# 2 1
# 3 c
# 4 d
如果您希望名称作为额外变量,请执行以下操作:
If you want the names as an extra variable, do this:
data.frame(V1=names(df), V2=unname(t(df)))
# V1 V2
# 1 a a
# 2 b 1
# 3 col3 c
# 4 col4 d
这篇关于pivot_longer 错误:无法组合不同的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!