I want to be able to replace values in a data frame by indexing by row and column, given a list of row indices, column names and values.
library(tidyverse)
cols <- sample(letters[1:10], 5)
vals <- sample.int(5)
rows <- sample.int(5)
df <- matrix(rep(0L, times = 50), ncol = 10) %>%
`colnames<-`(letters[1:10]) %>%
as_tibble
I can do this with a for loop over a list of the parameters:
items <- list(cols, vals, rows) %>%
pmap(~ list(..3, ..1, ..2))
for (i in items){
df[i[[1]], i[[2]]] <- i[[3]]
}
df
#> # A tibble: 5 x 10
#> a b c d e f g h i j
#> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
#> 1 0 0 0 0 0 0 0 1 0 0
#> 2 0 0 5 0 0 0 0 0 0 0
#> 3 0 0 0 0 0 0 4 0 0 0
#> 4 0 0 0 0 0 0 0 0 3 0
#> 5 0 0 0 0 0 0 0 0 0 2
but I feel like there should be an easier or "tidier" way to make all of the assignments at once, especially if there are many more than 5 items. Suppose that we know we won't get the same cell overwritten or anything (index combinations won't be duplicated), so the cell being modified will not change depending on what cycle you are on. You could call this question "vectorising assignment".