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

Replace the subsetted and modified data back into the main dataframe

I have a data frame with 20 rows, I randomly select n rows and modify them. How can I put the modified value back to the original data frame with only the modified value being different?

df<- data.frame(rnorm(n = 20, mean = 0, sd = 1))
n = 8
a<- data.frame(df[ c(1, sample(2:(nrow(df)-1), n), nrow(df) ), ])
a$changedvalue <- a[,1]*(2.5)

Now I want to replace the values of the original dataframe df with the values of a$changedvalue such that only the sampled values are changed while everything else is same in df. I tried doing something like this but it’s not working.

df %>% a[order(as.numeric(rownames(a))),]

I just want to point out that in my original dataset the data are timeseries data, so maybe they can be used for the purpose.

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

>Solution :

Instead of writing data.frame(df[ c(1, sample(2:(nrow(df)-1), n), nrow(df) ), ])

You can define the rows you want to use, lets call it rows

rows <- c(1, sample(2:(nrow(df)-1), n), nrow(df) )

Now you can do

a<- data.frame(df[rows, ])
a$changedvalue <- a[,1]*(2.5)

df[rows, ] <- a$changedvalue
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