Yandle
Yandle

Reputation: 411

How to swap row values in the same column of a data frame?

I have a data frame that looks like the following:

ID   Loc
 1    N  
 2    A   
 3    N
 4    H
 5    H  

I would like to swap A and H in the column Loc while not touching rows that have values of N, such that I get:

ID   Loc
 1    N  
 2    H   
 3    N
 4    A
 5    A 

This dataframe is the result of a pipe so I'm looking to see if it's possible to append this operation to the pipe.

Upvotes: 0

Views: 693

Answers (3)

Rich Scriven
Rich Scriven

Reputation: 99331

If you have a factor, you could simply reverse those levels

l <- levels(df$Loc)
l[l %in% c("A", "N")] <- c("N", "A")

df
#   ID Loc
# 1  1   A
# 2  2   N
# 3  3   A
# 4  4   H
# 5  5   H

Data:

df <- structure(list(ID = 1:5, Loc = structure(c(3L, 1L, 3L, 2L, 2L
), .Label = c("A", "H", "N"), class = "factor")), .Names = c("ID", 
"Loc"), class = "data.frame", row.names = c(NA, -5L))

Upvotes: 1

lroha
lroha

Reputation: 34441

You could try:

df$Loc <- chartr("AH", "HA", df$Loc)
df

  ID Loc
1  1   N
2  2   H
3  3   N
4  4   A
5  5   A

Upvotes: 3

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521259

We can try chaining together two calls to ifelse, for a base R option:

df <- data.frame(ID=c(1:5), Loc=c("N", "A", "N", "H", "H"), stringsAsFactors=FALSE)
df$Loc <- ifelse(df$Loc=="A", "H", ifelse(df$Loc=="H", "A", df$Loc))
df

  ID Loc
1  1   N
2  2   H
3  3   N
4  4   A
5  5   A

Upvotes: 2

Related Questions