gpt4 book ai didi

根据前一列的值替换多列中的值

转载 作者:行者123 更新时间:2023-12-03 20:25:41 25 4
gpt4 key购买 nike

我的样本数据看起来像这样(真实数据要大得多)

library(tidyverse, warn.conflicts = F)
df <- tibble(chr_x = c(0,0,1,1,1,4,4,4,5,5,6,7),
pos_x = c(1,2,3,4,5,6,7,8,9,0,1,2),
chr_y = c(1,2,3,3,3,2,1,1,0,0,1,5),
pos_some = c(1,2,3,4,5,6,7,8,9,0,1,2))

我需要将某些列中的某些值(假设以 chr 开头)替换为 NA我是这样做的

df %>% mutate_at(vars(starts_with("chr")), ~ na_if(., 0))
#> # A tibble: 12 x 4
#> chr_x pos_x chr_y pos_some
#> <dbl> <dbl> <dbl> <dbl>
#> 1 NA 1 1 1
#> 2 NA 2 2 2
#> 3 1 3 3 3
#> 4 1 4 3 4
#> 5 1 5 3 5
#> 6 4 6 2 6
#> 7 4 7 1 7
#> 8 4 8 1 8
#> 9 5 9 NA 9
#> 10 5 0 NA 0
#> 11 6 1 1 1
#> 12 7 2 5 2

下一部分是我陷入困境的地方。现在我需要将后续列中的值替换为 NA其中值是 NA在上面的列中。我怎样才能做到这一点?生成的 df 应如下所示

#> # A tibble: 12 x 4
#> chr_x pos_x chr_y pos_some
#> <dbl> <dbl> <dbl> <dbl>
#> 1 NA NA 1 1
#> 2 NA NA 2 2
#> 3 1 3 3 3
#> 4 1 4 3 4
#> 5 1 5 3 5
#> 6 4 6 2 6
#> 7 4 7 1 7
#> 8 4 8 1 8
#> 9 5 9 NA NA
#> 10 5 0 NA NA
#> 11 6 1 1 1
#> 12 7 2 5 2

创建于 2020-05-21 由 reprex package (v0.3.0)

最佳答案

利用 dplyr 的一种选择和 purrr可能:

bind_cols(df %>%
select(1) %>%
mutate_all(~ na_if(., 0)),
map_dfc(.x = 2:length(df),
~ df %>%
mutate_at(vars(starts_with("chr")), ~ na_if(., 0)) %>%
transmute_at(vars(.x), ~ replace(., !!is.na(select(., .x - 1)), NA))))

chr_x pos_x chr_y pos_some
<dbl> <dbl> <dbl> <dbl>
1 NA NA 1 1
2 NA NA 2 2
3 1 3 3 3
4 1 4 3 4
5 1 5 3 5
6 4 6 2 6
7 4 7 1 7
8 4 8 1 8
9 5 9 NA NA
10 5 0 NA NA
11 6 1 1 1
12 7 2 5 2

关于根据前一列的值替换多列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61941504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com