在 data.frame 中交换字符或字符串

Swap chars or strings in data.frame

我有一个 data.frame 的性别列:

Name <- c("Alex", "Lilly", "Mark", "Oliver", "Martha", "Lucas", "Caroline")
Age <- c(25, 31, 23, 52, 76, 49, 26)
Height <- c(177, 163, 190, 179, 163, 183, 164)
Weight <- c(57, 69, 83, 75, 70,  83, 53)
Sex <- c("F", "M", "F", "F", "M", "F", "M")

如您所见,性别不正确(例如,Lilly 的性别是 'M'),我想将所有的“F”换成 'M' 以及所有的 'M's 到 'F's。

有这个功能吗?

我想你可以在这里使用 ifelse:

df$Sex <- ifelse(df$Sex == "F", "M", "F")
df

      Name Age Height Weight Sex
1     Alex  25    177     57   M
2    Lilly  31    163     69   F
3     Mark  23    190     83   M
4   Oliver  52    179     75   M
5   Martha  76    163     70   F
6    Lucas  49    183     83   M
7 Caroline  26    164     53   F

Demo

或者,对于 dplyr 我们可以使用 case_when:

library(dplyr)

df %>% 
  mutate(Sex = case_when(Sex == "F" ~ "M",
                         Sex == "M" ~ "F",
                         TRUE ~ NA_character_))

数据:

Name <- c("Alex", "Lilly", "Mark", "Oliver", "Martha", "Lucas", "Caroline") 
Age <- c(25, 31, 23, 52, 76, 49, 26) 
Height <- c(177, 163, 190, 179, 163, 183, 164) 
Weight <- c(57, 69, 83, 75, 70, 83, 53) 
Sex <- c("F", "M", "F", "F", "M", "F", "M")

df <- data.frame(Name, Age, Height, Weight, Sex)

我们可以使用 chartr 来自 base R

df$Sex <- chartr("FM", "MF", df$Sex)
df$Sex
#[1] "M" "F" "M" "M" "F" "M" "F"

当一个因素时,使用:

df$Sex <- factor(df$Sex, c('F', 'M'), c('M', 'F'))