如何重新排列R中的单个细胞?

问题描述 投票:0回答:1
         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

在R中,你将如何交换“红苹果”和“蓝笼”的位置,以便它们在各自的列中。

例如。将Col2,Row4'Red Apple'与Col3,Row4'Blue Cage'交换

先感谢您。

r dataframe dplyr tidyr
1个回答
1
投票

这样做:

# 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
© www.soinside.com 2019 - 2024. All rights reserved.