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!
How do I mark a solution?
Find the reply you want to mark as the solution and look for the row of small gray icons at the bottom of that reply. Click the one that looks like a box with a checkmark in it:
[image]
Hovering over the mark solution button shows the label, "Select if this reply solves the problem". If you don't see the mark solution button, try clicking the three dots button ( ••• ) to expand the full set of options.
When a solution is chosen, the icon turns green and the hover label changes to: "Unselect if this reply no longer solves the problem". Success!
[solution_reply_author]
…
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.