SAJ
SAJ

Reputation: 320

Randomly insert 1's in columns of a data frame

I want to randomly insert 1's in the columns of a data frame that do not currently have 1 in them. Using different seeds for each of the variables.

Below is the code I have written so far:

# create the data frame
df <- data.frame(A = c(0,0,0,0,0,0,0,0,0,0), 
                    B = c(0,0,0,0,0,0,0,0,0,0),
                    C = c(0,1,0,0,0,1,0,1,0,0), 
                    D = c(0,0,0,0,0,0,0,0,0,0),
                    E = c(0,1,0,1,0,0,0,0,0,0))

# get index of columns that have 1's in them 
one_index <- which(grepl(pattern = 1, df))

# function to randomly put 1's with seperate seeds
funcccs <- function(x){
  i = 0
  for (i in 1:ncol(x)) {
    set.seed(i + 1)
    x[sample(nrow(x),3)] <- 1
}}

# Apply the function to the columns that do not have 1 
funcccs(df[,-one_index])

Below is the error message I get:

 Error in [<-.data.frame (*tmp*, sample(nrow(x), 3), value = 1) : 
  new columns would leave holes after existing columns 

Based on the above example, the function should randomly insert 3 values of 1 in variables 'A', 'B' and 'D', because these 3 variables do not currently have 1's in them.

Any help will be appreciated. Thanks

Upvotes: 0

Views: 44

Answers (1)

boski
boski

Reputation: 2467

df <- data.frame(A = c(0,0,0,0,0,0,0,0,0,0), 
                 B = c(0,0,0,0,0,0,0,0,0,0),
                 C = c(0,1,0,0,0,1,0,1,0,0), 
                 D = c(0,0,0,0,0,0,0,0,0,0),
                 E = c(0,1,0,1,0,0,0,0,0,0))
one_index <- which(grepl(pattern = 1, df))

funcccs <- function(x){
  i = 0
  for (i in 1:ncol(x)) {
    set.seed(i + 1)
    x[sample(nrow(x),3),i]= 1
  }
  return(x)
}
df[,-one_index]=funcccs(df[,-one_index])

You where choosing the whole matrix insted of the i column.

> df
   A B C D E
1  0 0 0 1 0
2  1 1 1 0 1
3  0 0 0 1 0
4  0 1 0 0 1
5  1 0 0 0 0
6  0 0 1 1 0
7  1 0 0 0 0
8  0 1 1 0 0
9  0 0 0 0 0
10 0 0 0 0 0

Upvotes: 2

Related Questions