R语言 根据另一列中的文本改变数据框

w6mmgewl  于 2023-05-04  发布在  其他
关注(0)|答案(1)|浏览(179)

实际上,我想根据列Region更改数据框。
我想检查列地区,如果有任何文字在列房子“!英国”在区域中,并为此添加一个新行,并粘贴文本在新行中的列房子。

library(tidyverse)
df <-  tibble(Region = c("AU","USA","CA","USA","!UK","AU","USA","CA","!UK"),
              lock = c(1,1,NA,1,NA,1,NA,1,NA),
              type= c("sale",NA,NA,"target","target",NA,"sale",NA,"target"),
              House =c("Tagore house","Gandhi house",NA,"Flexible;Tagore house;Gandhi house","Tagore house",NA,"Flexible;Gandhi house","Gandhi house","Gandhi house"))
6jygbczu

6jygbczu1#

我推断行顺序很重要。既然你没有任何暗示,我们将添加一个。

library(dplyr)
df <- mutate(df, rn = row_number())
df %>%
  filter(Region == "!UK") %>%
  transmute(House, rn = rn - 0.1) %>%
  bind_rows(df, .) %>%
  mutate(House = if_else(Region %in% "!UK", House[NA], House)) %>%
  arrange(rn)
# # A tibble: 11 × 5
#    Region  lock type   House                                 rn
#    <chr>  <dbl> <chr>  <chr>                              <dbl>
#  1 AU         1 sale   Tagore house                         1  
#  2 USA        1 <NA>   Gandhi house                         2  
#  3 CA        NA <NA>   <NA>                                 3  
#  4 USA        1 target Flexible;Tagore house;Gandhi house   4  
#  5 <NA>      NA <NA>   Tagore house                         4.9
#  6 !UK       NA target <NA>                                 5  
#  7 AU         1 <NA>   <NA>                                 6  
#  8 USA       NA sale   Flexible;Gandhi house                7  
#  9 CA         1 <NA>   Gandhi house                         8  
# 10 <NA>      NA <NA>   Gandhi house                         8.9
# 11 !UK       NA target <NA>                                 9

如果需要的话,可以使用select(-rn)(我保留它只是为了解释)。

相关问题