How to Swap Columns Around in a Data Frame Using R

Is it possible to swap columns around in a data frame using R?

dfrm <- dfrm[c("piglet", "ssire", "dam", "tdate")]

OR:

dfrm <- dfrm[ , c("piglet", "ssire", "dam", "tdate")]

Swap the first 2 columns in a data frame with 100 columns?

You can consider the following. dfrm is your target data frame.

dfrm <- dfrm[, c(2, 1, 3:ncol(dfrm))]

Since 3:ncol(dfrm) maintains the same column index as the original data frame, this code will preserve all the column order except the first two columns.

How to swap the values in two columns in R?

the easiest way to do this:

tmp <- df[1]
df[1] <- df[2]
df[2] <- tmp

How to swap the values in a two column subset in R?

We could create a logical index (either use grepl to check only digits (\\d+ - for numeric floats, use [0-9.]+ and assuming there are negative values -?) from start (^) to end ($) of string or reverse \\D any non-digit or may use as.numeric/as.integer and check with NA elements using is.na) and swap it by swapping the column names, then change the type of the columns with type.convert

i1 <- grepl("^-?[0-9.]+$", df$Sex)
df[i1, c("Sex", "Age")] <- df[i1, c("Age", "Sex")]
df <- type.convert(df, as.is = TRUE)

-output

> df
SequenceNo Sex Age
1. sequence1 Male 65
2. sequence2 Female 45
3. sequence3 Male 21
4. sequence4 Female 12
> str(df)
'data.frame': 4 obs. of 3 variables:
$ SequenceNo: chr "sequence1" "sequence2" "sequence3" "sequence4"
$ Sex : chr "Male" "Female" "Male" "Female"
$ Age : int 65 45 21 12

data

df <- structure(list(SequenceNo = c("sequence1", "sequence2", "sequence3", 
"sequence4"), Sex = c("Male", "Female", "21", "Female"), Age = c("65",
"45", "Male", "12")), class = "data.frame", row.names = c("1.",
"2.", "3.", "4."))

How to efficiently swap elements between columns in a dataframe?

# convert to character
dat[, c("R1", "R2")] <- lapply(dat[, c("R1", "R2")], as.character)

Next, we vectorize your row-change condition. All TRUE elements are those rows to be evaluated and swapped if necessary.

# get logical inidcator for elements to change
changeInd <- !!((match(dat$R2, levels(as.factor(dat$R2))) -
match(dat$R1, levels(as.factor(dat$R1)))) %% 2)

# perform swapping for given rows
dat[changeInd, c("R1", "R2")] <- dat[changeInd, c("R2", "R1")]

Here, we use match to select the rows where the changes are needed. After this, perform the simple swapping of variables with [.

This returns

dat
x R1 R2
1 1 D F
2 2 D D
3 3 F I
4 4 F I
5 5 D I
6 6 G I
7 7 I I
8 8 G Z
9 9 F G
10 10 A I

Note There may be a typo in the desired output. Since

identical((sapply(seq_len(nrow(dat)),
function(x) which(levels(as.factor(dat$R2)) %in% dat[x,'R2'], arr.ind = TRUE) -
which(levels(as.factor(dat$R1)) %in% dat[x,'R1'], arr.ind = TRUE)) %% 2) != 0,
changeInd)
[1] TRUE

data

dat <-
structure(list(x = 1:10, R1 = structure(c(1L, 1L, 4L, 4L, 1L,
3L, 4L, 5L, 2L, 4L), .Label = c("D", "F", "G", "I", "Z"), class = "factor"),
R2 = structure(c(3L, 2L, 3L, 3L, 5L, 5L, 5L, 4L, 4L, 1L), .Label = c("A",
"D", "F", "G", "I"), class = "factor")), .Names = c("x",
"R1", "R2"), class = "data.frame", row.names = c("1", "2", "3",
"4", "5", "6", "7", "8", "9", "10"))

How do I flip rows and columns in R

Assuming you have this data frame df, see data below.

  Country.Name 1997 1998 1999 2000
1 Country1 1 1 1 1
2 Country2 2 4 7 10
3 Country3 4 2 1 5

First you have to transpose all data frame except the first column. The result being a matrix that we need to convert to a data frame. Finally, we assign as column names of df2the first column of the original data frame df.

df2 <- data.frame(t(df[-1]))
colnames(df2) <- df[, 1]

Output:

     Country1 Country2 Country3
1997 1 2 4
1998 1 4 2
1999 1 7 1
2000 1 10 5

Data:

df <- structure(list(Country.Name = c("Country1", "Country2", "Country3"
), `1997` = c(1L, 2L, 4L), `1998` = c(1L, 4L, 2L), `1999` = c(1L,
7L, 1L), `2000` = c(1L, 10L, 5L)), .Names = c("Country.Name",
"1997", "1998", "1999", "2000"), class = "data.frame", row.names = c(NA,
-3L))

Moving columns within a data.frame() without retyping

Here is one way to do it:

> col_idx <- grep("g", names(df))
> df <- df[, c(col_idx, (1:ncol(df))[-col_idx])]
> names(df)
[1] "g" "a" "b" "c" "d" "e" "f"

How to swap values between variables in a data frame by column name in R

Given this input :

(df1 <- as.data.frame(matrix(1:12, ncol = 3)))
# V1 V2 V3
#1 1 5 9
#2 2 6 10
#3 3 7 11
#4 4 8 12

You can use rev

df1[1:2, c("V2", "V3")] <- rev(df1[1:2, c("V2", "V3")])

Result

df1
# V1 V2 V3
#1 1 9 5
#2 2 10 6
#3 3 7 11
#4 4 8 12

Written as a function of rows and cols

f <- function(data, rows, cols) {
data[rows, cols] <- rev(data[rows, cols])
data
}

f(df1, 1:2, c("V2", "V3"))


Related Topics



Leave a reply



Submit