![](/img/trans.png)
[英]Create a column that assigns value to a row in a dataframe based on an event in another row
[英]Changing the value of a row based on another row from a different column
我有一個包含A和B列的數據框。我需要編寫一個函數,該函數接受A中的所有空值並根據B中的值替換它們。如果B列中的值是“很好”或“很好” ,則應在A中放置“家”。如果B列中的值為“ Fair”或“ Bad”,則應在其中放置“ Foreign”。最后,如果B列中的值是“ Very Bad”或“最差”,則應將“中央”放在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
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
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.