Reputation: 5897
I am working with the R programming language. Suppose I have the following data frame:
a = rnorm(100,10,1)
b = rnorm(100,10,5)
c = rnorm(100,10,10)
my_data = data.frame(a,b,c)
head(my_data)
a b c
1 9.623328 10.560865 18.520644
2 7.805709 14.550575 1.144607
3 9.290704 16.597876 26.662429
4 8.828285 10.229534 -8.228798
5 9.454419 5.059026 18.454799
6 9.835949 16.778726 2.372435
My Question: For each variable in this data frame, I want to randomly replace 50% of these numbers with 0.
Here is a inefficient way I thought of to do this:
my_data$a_new <- sample( LETTERS[1:2], 100, replace=TRUE, prob=c(0.5, 0.5) )
my_data$b_new <- sample( LETTERS[1:2], 100, replace=TRUE, prob=c(0.5, 0.5) )
my_data$c_new <- sample( LETTERS[1:2], 100, replace=TRUE, prob=c(0.5, 0.5) )
my_data$a_new2 = ifelse(my_data$a_new == "A", my_data$a, 0)
my_data$b_new2 = ifelse(my_data$b_new == "B", my_data$b, 0)
my_data$c_new2 = ifelse(my_data$b_new == "C", my_data$c, 0)
Is there a more efficient way to do this?
Upvotes: 2
Views: 234
Reputation: 388797
You may use lapply
-
my_data[] <- lapply(my_data, function(x) {
x[sample(seq_along(x), length(x)/2)] <- 0
x
})
If for different columns you have a difference percentage to replace with 0 you may use Map
.
perc <- c(0.2, 0.4, 0.5)
my_data[] <- Map(function(x, y) {
x[sample(seq_along(x), length(x) * y)] <- 0
x
}, my_data, perc)
Upvotes: 2