Search code examples
rvectorrandomreplaceswap

Randomly swap a certain amount of entries in two different columns in a data frame in R


I have simulated two vectors from a binomial distribution. Both vectors have a different probability of success. Now I have merged them together into a data frame and I need to swap 50 column entries randomly (i.e. put 50 random entries from B into A and put 50 random entries from A into B). I have done the following but I am wondering if I can do the same in one code only. Now I have to assume that R takes some random values from B into A and then puts them back from A into B, which I don't want to happen.

test_a <- rbinom(100, 1, 0.2)
test_b <- rbinom(100, 1, 0.5)

a_name <- "A"
b_name <- "B"

test <- data.frame(test_a,test_b)
names(test) <- c(a_name, b_name)


test$A[sample(nrow(test), 50)] <- sample(test$B, 50)
test$B[sample(nrow(test), 50)] <- sample(test$A, 50) 

Solution

  • Maybe this is what you are looking for -

    n <- sample(nrow(test), 50)
    test[n, 1:2] <- test[n, 2:1]