我需要转置一个大型数据框,所以我使用:
df.aree <- t(df.aree)
df.aree <- as.data.frame(df.aree)
Run Code Online (Sandbox Code Playgroud)
这是我获得的:
df.aree[c(1:5),c(1:5)]
10428 10760 12148 11865
name M231T3 M961T5 M960T6 M231T19
GS04.A 5.847557e+03 0.000000e+00 3.165891e+04 2.119232e+04
GS16.A 5.248690e+04 4.047780e+03 3.763850e+04 1.187454e+04
GS20.A 5.370910e+03 9.518396e+03 3.552036e+04 1.497956e+04
GS40.A 3.640794e+03 1.084391e+04 4.651735e+04 4.120606e+04
Run Code Online (Sandbox Code Playgroud)
我的问题是我需要消除的新列名称(10428,10760,12148,11865),因为我需要将第一行用作列名.
我试过col.names()
功能,但我没有得到我需要的东西.
你有什么建议吗?
编辑
谢谢你的建议!使用它我获得:
df.aree[c(1:5),c(1:5)]
M231T3 M961T5 M960T6 M231T19
GS04.A 5.847557e+03 0.000000e+00 3.165891e+04 2.119232e+04
GS16.A 5.248690e+04 4.047780e+03 3.763850e+04 1.187454e+04
GS20.A 5.370910e+03 9.518396e+03 3.552036e+04 1.497956e+04
GS40.A 3.640794e+03 1.084391e+04 4.651735e+04 4.120606e+04
GS44.A 1.225938e+04 2.681887e+03 1.154924e+04 4.202394e+04
Run Code Online (Sandbox Code Playgroud)
现在我需要在因子列中转换行名(GS ..)....
Tom*_*mmy 98
你最好不要在名称列所在的位置转置data.frame - 然后所有的数值都会变成字符串!
这是一个将数字保持为数字的解决方案:
# first remember the names
n <- df.aree$name
# transpose all but the first column (name)
df.aree <- as.data.frame(t(df.aree[,-1]))
colnames(df.aree) <- n
df.aree$myfactor <- factor(row.names(df.aree))
str(df.aree) # Check the column types
Run Code Online (Sandbox Code Playgroud)
Fra*_*ank 46
df.aree <- as.data.frame(t(df.aree))
colnames(df.aree) <- df.aree[1, ]
df.aree <- df.aree[-1, ]
df.aree$myfactor <- factor(row.names(df.aree))
Run Code Online (Sandbox Code Playgroud)
raf*_*ira 36
您可以使用库中的transpose
功能data.table
.简单快速的解决方案,将numeric
价值保持为numeric
.
library(data.table)
# get data
data("mtcars")
# transpose
t_mtcars <- transpose(mtcars)
# get row and colnames in order
colnames(t_mtcars) <- rownames(mtcars)
rownames(t_mtcars) <- colnames(mtcars)
Run Code Online (Sandbox Code Playgroud)
使用tidyr,可以使用“pivot_longer”然后“pivot_wider”转置数据帧。
要转置广泛使用的 mtcars 数据集,您应该首先将 rownames 转换为列(函数rownames_to_column创建一个新列,名为“rowname”)。
library(tidyverse)
mtcars %>%
rownames_to_column() %>%
pivot_longer(!rowname, names_to = "col1", values_to = "col2") %>%
pivot_wider(names_from = "rowname", values_from = "col2")
Run Code Online (Sandbox Code Playgroud)