Reputation: 452
I've been reading another question about how to randomly subset rows of a dataframe, but I'm trouble figuring out how to change the values of a particular column in the dataframe for a random subset of the rows.
from Sample random rows in dataframe :
df = data.frame(matrix(rnorm(20), nrow=10))
df[sample(nrow(df), 3), ]
How do I replace randomly selected rows of the X1 column with 0's, for instance?
Thanks!
Upvotes: 0
Views: 1079
Reputation: 613
Or you can use data.table
package:
library(data.table)
df = data.table(matrix(rnorm(20), nrow=10))
df[sample(.N,3), V1 := 0]
Except for that the default colnames would be changed to 'V1''V2'...
Upvotes: 2
Reputation: 11762
You just need to select the column before setting the new value.
df = data.frame(matrix(rnorm(20), nrow=10))
df[sample(nrow(df), 3), 'X1'] <- 0
Upvotes: 3