This is a test version of Biostars. For the public version, visit https://www.biostars.org.
replaceing 20 percent of values based on another column in R

Hi, I have a dataframe like this.

gen <- rep(c("1","2"), each=10)
phen = seq(from = 1, to = 20, by = 1)
y <- data.frame(gen, phen)

I want to based on each group of gen (1 and 2) replace 20 percent of phen to 0. How i can do that? Tnx

r

1 answer

tidyverse solution

library("dplyr")

y <- y %>%
  group_by(gen) %>%
  mutate(phen=if_else(cur_group_rows() %in% sample(cur_group_rows(), n()*0.2), 0, phen))

> y
# A tibble: 20 x 2
# Groups:   gen [2]
   gen    phen
   <chr> <dbl>
 1 1         1
 2 1         0
 3 1         3
 4 1         0
 5 1         5
 6 1         6
 7 1         7
 8 1         8
 9 1         9
10 1        10
11 2        11
12 2        12
13 2        13
14 2        14
15 2         0
16 2        16
17 2        17
18 2         0
19 2        19
20 2        20

Thanks Is that another way without using special package?

Log in to answer this question.