How to turn column into row in dataframe

Asked

Viewed 123 times

0

I have two dataframes and would like to transform the data of the two columns of the 2nd df into rows to be added in sequence of the data of the 1st df. To illustrate create the two df and the final result.

df1 = data.frame(c("MG","SP","RJ","ES","PA"),c("PA","ES","MG","SP","RJ"))

colnames(df1) = c("Nome", "Estado")

df2 = data.frame(c("PA","ES","MG","SP","RJ"),c("MG","SP","RJ","ES","PA"))

colnames(df2) = c("Estado", "Nome")

The result would turn df into 10 notes with 2 columns:

df3 = data.frame(c("MG","SP","RJ","ES","PA","PA","ES","MG","SP","RJ"),c("PA","ES","MG","SP","RJ","MG","SP","RJ","ES","PA"))

colnames(df3) = c("Nome", "Estado")
  • 2

    rbind.data.frame(df1, df2)?

2 answers

2

To unite lines of different s you can use the rbind package base or the bind_row of .

Then we would have:

library(tidyverse)

df4 <- bind_rows(df1, df2)
df5 <- rbind(df1, df2)
identical(df4, df5)
#> [1] TRUE

Note however that the response obtained is not the same as the one you created on df3.

identical(df3, df4)
#> [1] FALSE

This is because both functions understand that observations of variables with the same name must be joined under this variable and df1and df2 has the names of the inverted columns.

To produce the df3 result simply change the names of df2.

df5 <- bind_rows(df1, set_names(df2, c("Nome", "Estado")))
identical(df3, df5)
#> [1] TRUE

0

Use the rbind function

df1 = data.frame(c("MG","SP","RJ","ES","PA"),c("PA","ES","MG","SP","RJ"))

colnames(df1) = c("Nome", "Estado")

df2 = data.frame(c("PA","ES","MG","SP","RJ"),c("MG","SP","RJ","ES","PA"))

colnames(df2) = c("Estado", "Nome")


df3<- rbind(df1, df2)
df3

Browser other questions tagged

You are not signed in. Login or sign up in order to post.