R语言 如何在具有特定标题名称列下有条件地更改行值

rqdpfwrv  于 2023-02-06  发布在  其他
关注(0)|答案(1)|浏览(106)

我有一个数据集,如下所示:

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)

请只使用特殊的字母大小写,尽可能长。我想做的是创建一个代码,这样每次在名称中包含单词'Prosz'的列下,都有一行值为' A ',相邻行的值应该为NA。如何使用tidyverse,迭代函数或通过循环来实现这一点?

最简单的预期结果

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
rpppsulh

rpppsulh1#

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))))
  • 输出
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

相关问题