Question: replaceing 20 percent of values based on another column in R
0
gravatar for mlganjnameh
2 days ago by
mlganjnameh0 wrote:

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 • 71 views
ADD COMMENTlink modified 2 days ago by rpolicastro1.9k • written 2 days ago by mlganjnameh0
1
gravatar for rpolicastro
2 days ago by
rpolicastro1.9k
rpolicastro1.9k wrote:

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
ADD COMMENTlink modified 2 days ago • written 2 days ago by rpolicastro1.9k

Thanks Is that another way without using special package?

ADD REPLYlink written 2 days ago by mlganjnameh0
Please log in to add an answer.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 2204 users visited in the last hour