I'm pretty sure there's a way to get there, but I'm not able to find it.
I have a data frame with several columns. I now want to add new columns to my data frame containing the info when sampling from these columns (0/1). I have a tidy solution with across that works if I want to sample the same number of elements from each column. I also have a (even uglier) solution with across when sampling different number of elements from each column, but I was hoping for an easier solution with purrr where I just provide the column names as one argument and the number of elements to be sampled as another argument and then would get my new columns.
Any ideas?
Data
df <- data.frame(x = runif(10),
y = runif(10),
z = runif(10))
df[1, 1] <- NA
df[2, 2] <- NA
df[3, 3] <- NA
sampling <- c(2, 3, 4)
names(sampling) <- c("random_x", "random_y", "random_z")
Solution for sampling the same number of elements
df %>%
mutate(across(everything(),
~if_else(is.na(.),
NA_integer_,
as.integer(row_number() %in% sample(which(!is.na(.)), size = 3))),
.names = "{.col}_random"))
Solution for sampling a different number of elements
df %>%
mutate(across(everything(),
~if_else(is.na(.),
NA_integer_,
as.integer(row_number() %in% sample(which(!is.na(.)), size = sampling[str_detect(names(sampling), paste0(cur_column(), "$"))]))),
.names = "{.col}_random"))
Desired purrr way
Sth. along those lines maybe?
df %>%
map2(.x = c("x", "y", "z"),
.y = sampling,
.f = ~if_else(is.na(.x),
NA_integer_,
as.integer(row_number() %in% sample(which(!is.na(.x)), size = .y))))
Problem with the purrr way obviously is that I don't use the right syntax because I'm passing a character vector as .x and not columns from df.
Desired output
(leaving the randomness of the results aside)
x y z x_random y_random z_random
1 NA 0.06686268 0.7663706 NA 0 0
2 0.7551366 NA 0.5550793 0 NA 1
3 0.7437531 0.61971712 NA 0 0 NA
4 0.5238451 0.57510689 0.7637622 1 0 0
5 0.9593917 0.17481769 0.4443493 0 0 0
6 0.2821633 0.86972254 0.2284449 0 0 0
7 0.3941531 0.61981285 0.8202302 0 0 1
8 0.1473573 0.58482156 0.9078447 0 1 1
9 0.7063327 0.77550907 0.9271699 1 1 1
10 0.6320678 0.06011700 0.2139956 0 1 0