简体   繁体   中英

how to change conditionally row values when under column with specific header name

I have a dataset like the following one:

ProszęAveryextendedname <- c("A","A","A","A","B","B","B")
var2 <- c("B","B","B","B","B","B","B")
var3 <- c("B","B","B","B","B","B","B")

ProszęBveryextendedname <- c("A","A","A","A","B","B","B")
var5 <- c("B","B","B","B","B","B","B")
var6 <- c("B","B","B","B","B","B","B")

df <- data.frame(ProszęAveryextendedname , var2, var3, ProszęBveryextendedname, var5, var6)

please just to the special alphabet case, as long as possible. What I would like to do is to create a code so that every time under the column that has in its name head the word 'Proszę', there is a row with value 'A', the adjacent rows should have a NA value. How would it be possible to make this with a tidyverse, iterative function or via a loop?

SIMPLEST EXPECTED OUTCOME

  ProszeAveryextendedname var2 var3     ProszeBveryextendedname var5 var6
1                       A    NA    NA                       A    NA    NA
2                       A    NA    NA                       A    NA    NA
3                       A    NA    NA                       A    NA    NA
4                       A    NA    NA                       A    NA    NA
5                       B    B    B                         B    B      B
6                       B    B    B                         B    B      B
7                       B    B    B                         B    B      B
library(dplyr)
library(purrr)
ind <- grepl("Proszę", names(df));
df <- purrr::map_dfc(split.default(df, cumsum(ind)), 
 ~ .x %>% mutate(across(-1, 
    ~ replace(.x, cur_data()[[1]] == "A", NA))))

-output

df
  ProszęAveryextendedname var2 var3 ProszęBveryextendedname var5 var6
1                       A <NA> <NA>                       A <NA> <NA>
2                       A <NA> <NA>                       A <NA> <NA>
3                       A <NA> <NA>                       A <NA> <NA>
4                       A <NA> <NA>                       A <NA> <NA>
5                       B    B    B                       B    B    B
6                       B    B    B                       B    B    B
7                       B    B    B                       B    B    B

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM