0

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!

Community
  • 1
  • 1
Jay
  • 442
  • 1
  • 5
  • 13

2 Answers2

3

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
drmariod
  • 11,106
  • 16
  • 64
  • 110
2

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'...

Frank
  • 66,179
  • 8
  • 96
  • 180
Feng
  • 603
  • 3
  • 9