【问题标题】:How to rearrange individual cells in R?如何重新排列R中的单个单元格?
【发布时间】:2018-07-21 07:58:25
【问题描述】:
         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' 交换

提前谢谢你。

【问题讨论】:

  • df$Col2 = "Red Apple" ?这有帮助吗?
  • 感谢这绝对有效!但是,我更多的是指交换单元格。例如。将 Col2, Row4 'Red Apple' 与 Col3, Row4 'Blue Cage' 交换。谢谢
  • 您是否只是想交换两列?喜欢df[c("Col2","Col3")] <- df[c("Col3","Col2")]

标签: r dataframe dplyr tidyr


【解决方案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

【讨论】:

  • 非常感谢!这绝对有帮助。
猜你喜欢
  • 1970-01-01
  • 2017-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多