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.
CodePudding user response:
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