Jason
Jason

Reputation: 3

How to rearrange individual cells in R?

         Col1          Col2          Col3
Row1     Pink rose     Red Apple     Blue Cage
Row2     Pink rose     Red Apple     Blue Cage
Row3     Pink rose     Blue Cage     Red Apple
Row4     Pink rose     Red Apple     Blue Cage
Row5     Pink rose     Blue Cage     Red Apple

In R, how would you swap around the positions of "Red Apple" and "Blue Cage" so that they are in their respective columns.

eg. swapping Col2, Row4 'Red Apple' with Col3, Row4 'Blue Cage'

Thank you in advance.

Upvotes: 0

Views: 87

Answers (1)

stevec
stevec

Reputation: 52528

This will do it:

# Your original dataframe
df <- data.frame(Col1=c("Pink Rose", "Pink Rose", "Pink Rose", "Pink Rose", "Pink Rose"),
                 Col2=c("Red Apple", "Red Apple", "Blue Cage", "Red Apple", "Blue Cage"),
                 Col3=c("Blue Cage", "Blue Cage", "Red Apple", "Blue Cage", "Red Apple"))
row.names(df) <- c("Row1", "Row2", "Row3", "Row4", "Row5")
df

# Find "Blue Cage" in Col2 and replace them with "Red Apple":
df$Col2[df$Col2 == "Blue Cage"] <- "Red Apple"

# and find "Red Apple" in Col3 and replace them with "Blue Cage" 
df$Col3[df$Col3 == "Red Apple"] <- "Blue Cage"
df

Upvotes: 1

Related Questions