replaceing 20 percent of values based on another column in R
1
0
Entering edit mode
8 months ago

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 • 192 views
ADD COMMENT
1
Entering edit mode
8 months ago

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 COMMENT
0
Entering edit mode

Thanks Is that another way without using special package?

ADD REPLY

Login before adding your answer.

Traffic: 2006 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6