Hi guys,
sorry for the question, perhaps trivial.
I have to reverse the rows with the columns. i mean i have a dataframe like:
V1 V2
1 Gender Male
2 Weight 75 kg
3 Height 175 cm
4 Age 21
i would like to get:
Gender Weight Height Age
Male 75kg 175cm 21
This is one way to do it
df <- data.frame(stringsAsFactors = FALSE,
V1 = c("Gender", "Weight", "Height", "Age"),
V2 = c("Male", "75 kg", "175 cm", "21")
)
rownames(df) <- df$V1
df$V1 <- NULL
df <- as.matrix(df)
df <- as.data.frame(t(df))
rownames(df) <- NULL
df
#> Gender Weight Height Age
#> 1 Male 75 kg 175 cm 21
Created on 2019-02-07 by the reprex package (v0.2.1)
2 Likes
You can simply use the transpose of a data frame i.e. t(df)
where df
is name of your data frame. For more information read https://www.r-statistics.com/tag/transpose/
1 Like
If your question's been answered (even by you!), would you mind choosing a solution? It helps other people see which questions still need help, or find solutions if they have similar problems. Here’s how to do it:
If your question has been answered don't forget to mark the solution
Folks in the future can come along and easily see what worked for you.
You acknowledge the person who solved the issue.
If you're the original poster and the category allows solutions to be marked there should be a little box at the bottom of replies that you can click to select that response as your "solution."
Before:
[image]
After:
[image]
Based on replies by @mara
grrrck
February 7, 2019, 6:47pm
6
Here's another approach, using spread()
from the tidyr package.
library(tidyr)
df <- data.frame(stringsAsFactors = FALSE,
V1 = c("Gender", "Weight", "Height", "Age"),
V2 = c("Male", "75 kg", "175 cm", "21")
)
df
#> V1 V2
#> 1 Gender Male
#> 2 Weight 75 kg
#> 3 Height 175 cm
#> 4 Age 21
spread(df, V1, V2)
#> Age Gender Height Weight
#> 1 21 Male 175 cm 75 kg
Created on 2019-02-07 by the reprex package (v0.2.1)
2 Likes
system
Closed
February 28, 2019, 6:58pm
7
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed. If you have a query related to it or one of the replies, start a new topic and refer back with a link.