Home > Net >  Random value in column in R
Random value in column in R

Time:06-01

Does anyone have an idea how to generate column of random values where only one random row is marked with number "1". All others should be "0". I need function for this in R code. Here is what i need in photos: enter image description here

CodePudding user response:

df <- data.frame(subject = 1, choice = 0, price75 = c(0,0,0,1,1,1,0,1))

This command will update the choice column to contain a single random row with value of 1 each time it is called. All other rows values in the choice column are set to 0.

df$choice <-  (seq_along(df$choice) == sample(nrow(df), 1))

CodePudding user response:

With integer(length(DF$choice)) a vector of 0 is created where [<- is replacing a 1 on the position from sample(length(DF$choice), 1).

DF <- data.frame(subject=1, choice="", price75=c(0,0,0,1,1,1,0,1))

DF$choice <- `[<-`(integer(nrow(DF)), sample(nrow(DF), 1), 1)
DF
# subject choice price75
#1       1      0       0
#2       1      0       0
#3       1      0       0
#4       1      1       1
#5       1      0       1
#6       1      0       1
#7       1      0       0
#8       1      0       1

CodePudding user response:

> x <- rep(0, 10)
> x[sample(1:10, 1)] <- 1
> x
 [1] 0 0 0 0 0 0 0 1 0 0

CodePudding user response:

Many ways to set a random value in a row\column in R

df<-data.frame(x=rep(0,10)) #make dataframe df, with column x, filled with 10 zeros.
set.seed(2022)              #set a random seed - this is for repeatability
#two base methods for sampling:
#sample.int(n=10, size=1)   # sample an integer from 1 to 10, sample size of 1
#sample(x=1:10, size=1)     # sample from 1 to 10, sample size of 1
df$x[sample.int(n=10, size=1)] <- 1  # randomly selecting one of the ten rows, and replacing the value with 1
df
  •  Tags:  
  • r
  • Related