如何将单列长数据框转换为单行宽数据框?

huangapple go评论68阅读模式
英文:

How to pivot a single column long dataframe into a single row wide dataframe?

问题

只有代码部分需要翻译:

我看到在Stack Overflow和其他在线地方有许多关于将数据框转换为宽格式和长格式的问题。但我没有看到任何清晰、简单的示例,只是将单列数据框转换或透视为单行“宽格式”数据框。有没有建议可以轻松实现这一目标的方法?我可以使用基本的R、dplyr、data.table、tidyr等。下面我展示了我尝试做的事情,附有一个超简单的单列数据框的代码示例,这正好代表了我正在处理的较大响应数据框。非常重要的是要保留我的“test”数据框的“row.names”并将它们转置为新透视数据框的列名,而不仅仅是一个2行数据框的第一行。
英文:

I see there are many questions on Stack Overflow and other places online regarding pivoting dataframes into wide and long format. But I don't see any clear, simple examples of just transposing or pivoting a single column dataframe into a single row, "pivot wide" dataframe. Any recommendations for an easy way to do this? I'm fine with base R, dplyr, data.table, tidyr, etc. Below I illustrate what I'm trying to do, with the code for a super-simple single column dataframe at the bottom. This is exactly representative of the larger reactive dataframe I'm wrestling with. Very important to preserve the row.names of my test dataframe and transpose them into column names for the new pivoted data frame, and they need to be column names and not just a first row of a 2 row dataframe.

如何将单列长数据框转换为单行宽数据框?

Code for example dataframe:

test <- data.frame(c(1:5), row.names = LETTERS[1:5])

答案1

得分: 2

在转置后更容易

作为数据框(t(未命名(test)))
A B C D E
1 1 2 3 4 5


<details>
<summary>英文:</summary>

It is easier after transposing

as.data.frame(t(unname(test)))
A B C D E
1 1 2 3 4 5


</details>



huangapple
  • 本文由 发表于 2023年3月4日 02:46:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75630805.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定