我有一个带有A和B列的数据框。我需要编写一个函数,该函数接受A中的所有空值并根据B中的值替换它们。如果B列中的值是'很好'或“好”,则应在“ A”中放置“家”。如果B列中的值为“ Fair”或“ Bad”,则应在A中放置“ Foreign”。最后,如果B列中的值是“非常糟糕”或“最差”,则应将“中央”放在A中。
#Here's the data:
df <- structure(list(`A` = c("Home", NA, "Foreign", NA, "Central", NA),
`B` = c("Good", "Very Good", "Bad", "Fair", "Very Bad", "Worst")),
row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))
#Here's how the data look
A B
1 Home Good
2 NA Very Good
3 Foreign Bad
4 NA Fair
5 Central Very Bad
6 NA Worst
#Here's the expected result
A B
1 Home Good
2 Home Very Good
3 Foreign Bad
4 Foreign Fair
5 Central Very Bad
6 Central Worst
答案 0 :(得分:2)
library(dplyr)
df %>% mutate(tmp = case_when(B %in% c("Good", "Very Good") ~ "Home",
B %in% c("Bad", "Fair") ~ "Foreign",
B %in% c("Very Bad", "Worst") ~ "Central")) %>%
mutate(A = if_else(is.na(A),tmp,A)) %>%
select(-tmp)
#> # A tibble: 6 x 2
#> A B
#> <chr> <chr>
#> 1 Home Good
#> 2 Home Very Good
#> 3 Foreign Bad
#> 4 Foreign Fair
#> 5 Central Very Bad
#> 6 Central Worst
答案 1 :(得分:1)
library(tidyverse)
df <- structure(list(`A` = c("Home", NA, "Foreign", NA, "Central", NA),
`B` = c("Good", "Very Good", "Bad", "Fair", "Very Bad", "Worst")),
row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))
df %>%
mutate(AA = ifelse(B %in% c("Good", "Very Good"), "Home", ifelse(B %in% c("Bad", "Fair"), "Foreign", ifelse(B %in% c("Very Bad", "Worst"), "Central", NA))),
A = ifelse(is.na(A), AA, A))
#> # A tibble: 6 x 3
#> A B AA
#> <chr> <chr> <chr>
#> 1 Home Good Home
#> 2 Home Very Good Home
#> 3 Foreign Bad Foreign
#> 4 Foreign Fair Foreign
#> 5 Central Very Bad Central
#> 6 Central Worst Central