Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert part of the values in rows in a data frame

I have a data frame which looks like this:

df

colA colB
0     0
1     1
0     1
0     1
0     1
1     0
0     0
1     1
0     1

I would like to convert a certain proportion of the 0 in colA to NA and a certain proportion of 1 in colB to NA

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if I do this:

df["colA"][df["colA"] == 0] <- NA

all the 0 in columns A will be converted to NA, however I just want half of them to be converted

Similarly, for colB I want only 1/3 of the 1 to be converted:

df["colB"][df["colB"] == 1] <- NA

Expected output:

   colA colB
    0     0
    1     1
    NA    1
    0     1
    NA    1
    1     0
    0     0
    1     NA
    NA    NA

>Solution :

One way

tmp=which(df["colA"]==0)
df$colA[sample(tmp,round(length(tmp)/2))]=NA

similar for colB

tmp=which(df["colB"]==1)
df$colB[sample(tmp,round(length(tmp)/3))]=NA
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading