转置数据框,将第一列保持为标题
我有一个大数据框,但小例子如下:
mydf <- data.frame(A = c(letters[1:10]), M1 = c(11:20), M2 = c(31:40), M3 = c(41:50))
我想转置数据框并将列 1 (A) 维护为列标题(字母 [1:10])作为变量名称。以下是不成功代码的临时尝试。
tmydf = data.frame(t(mydf))
names(tmydf) <- tmydf[1,]
谢谢;
I have a big dataframe, but small example would be like this:
mydf <- data.frame(A = c(letters[1:10]), M1 = c(11:20), M2 = c(31:40), M3 = c(41:50))
I want to transpose the dataframe and maintain the column 1 (A) as column heading ( letter[1:10]) as variable names. The following are scratch trials of unsuccessful codes.
tmydf = data.frame(t(mydf))
names(tmydf) <- tmydf[1,]
Thanks;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是一种方法
Here is one way
也许是这样的:
Something like this perhaps:
您可以使用
tidyr
包中的pivot_longer
和pivot_wider
函数。pivot_longer
创建一个名为“Original_Vars”的列,以及一个名为value
的新列。如果您停在这里,您的A
变量、“Original_Vars”(此处为 M1、M2 和 M3)以及与该配对关联的值的每个组合都会有一行。然后,
pivot_wider
从“A”列中获取所有值,并使用我们通过pivot_longer
value 列中的值将它们转换为列> 来填写。You can use the
pivot_longer
andpivot_wider
functions from thetidyr
package.The
pivot_longer
makes a column called "Original_Vars", and a new column calledvalue
. If you stopped here, you'd have a row for each combination of yourA
variable, your "Original_Vars" (being M1, M2, and M3 here), and the value associated with that pairing.The
pivot_wider
then takes all your values from the "A" column and turns them into columns, using the values from thevalue
column we created withpivot_longer
to fill in.另一种将
janitor::row_to_names()
与dplyr
/magrittr
管道结合使用的方法由 reprex 包 (v2.0.0)
One more way using
janitor::row_to_names()
withdplyr
/magrittr
pipesCreated on 2021-06-17 by the reprex package (v2.0.0)
来自 Ramnath 的 Data.table Variablee,在字符串中指示所需的变量名称。
Data.table variante from Ramnath with indicating in string the variable name wanted.