I am working with data with multiple row headers. I am willing to add these headers into data.
EX: I want to change this
X
A 1
B 2
C 3
D 4
E 5
into this
Y X
A 1
B 2
C 3
D 4
E 5
I want to keep Y and X as headers but make A,B,C,D,E are column values.
We can use rownames_to_column
from tibble
library(tibble)
library(dplyr)
df1 %>%
rownames_to_column("Y")
-output
# Y X
#1 A 1
#2 B 2
#3 C 3
#4 D 4
#5 E 5
Or with data.frame
data.frame(Y = row.names(df1), X = df1$X)
-output
# Y X
#1 A 1
#2 B 2
#3 C 3
#4 D 4
#5 E 5
NOTE: Both are single line codes
df1 <- structure(list(X = 1:5), class = "data.frame", row.names = c("A",
"B", "C", "D", "E"))
You can also try:
#Code
new <- as.data.frame(cbind(Y=rownames(df),df),row.names = NULL)
rownames(new)<-NULL
Output:
new
Y X
1 A 1
2 B 2
3 C 3
4 D 4
5 E 5
Some data used:
#Data
df <- structure(list(X = 1:5), class = "data.frame", row.names = c("A",
"B", "C", "D", "E"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.