How I can swap 2 colmn of a data set in R? for example I have
1 56
2 43
3 42
4 32
and I want to have
56 1
43 2
42 3
32 4
We can do the reverse sequence (generalized)
df2 <- df1[ncol(df1):1]
or for a two column, it is
df1[2:1]
If the OP wants to select only a particular column
df2 <- df1[c(6, 1:5)]
With tidyverse
library(dplyr)
df2 <- df1 %>%
select(6, everything())
You can choose an arbitary order if you would like.
library(tidyverse)
df %>%
select(col3,col4,col2,col1)
df <- data.frame(c1 = 1:4, c2 = c(56, 43, 42, 32))
df
# c1 c2
#1 1 56
#2 2 43
#3 3 42
#4 4 32
df[c(2,1)]
# c2 c1
#1 56 1
#2 43 2
#3 42 3
#4 32 4
You can swap by changing the locations within c
(combine):
df <- data.frame(c1=1:4, c2=c(56,43,42,32), c3=c(12,13,14,15));df
# c1 c2 c3
#1 1 56 12
#2 2 43 13
#3 3 42 14
#4 4 32 15
df[c(3,1,2)]
# c3 c1 c2
#1 12 1 56
#2 13 2 43
#3 14 3 42
#4 15 4 32