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

时间:2018-03-07 13:46:03

标签: r string swap chars

我有一个包含Sex:

列的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'换成'F'。

那是否有功能?

4 个答案:

答案 0 :(得分:6)

我们可以使用chartr

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

答案 1 :(得分:3)

我认为你可以在这里使用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

答案 2 :(得分:2)

或者,使用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)

答案 3 :(得分:1)

当一个因素时,使用:

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