Jay
Jay

Reputation: 452

In R, how do I change the values for a specific column in a random set of rows?

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

Answers (2)

Feng
Feng

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

drmariod
drmariod

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

Related Questions