Igor Cobelo
Igor Cobelo

Reputation: 459

Move columns from a data frame below other columns in R

I have a data frame with 4 columns and 20 rows. I would like to move the last two columns to be below the other two, resulting in 2 columns and 40 rows. Is there any function in R so that I can select as argument the value of columns I want to move (2) without being manually? I ask this because I need it in a for loop. Thanks.

Upvotes: 2

Views: 1126

Answers (1)

akrun
akrun

Reputation: 887951

We can use use.names = FALSE in unlist

df2 <- data.frame(col1 = unlist(df1, use.names = FALSE))

if needed, assign the rownames to NULL

row.names(df2) <- NULL

For the first case, rbind the subset of columns after making the column names same as the first 2 columns

rbind(df1[1:2], setNames(df1[3:4], names(df1)[1:2]))

Upvotes: 2

Related Questions