How to create multiple columns with index function in R?

Viewed 63

I would like to create a k number of columns in R determined by an index k that is also part of the underlying function.

Data for replication:

D_s<-c(34,36,27,23,30,49,60)
S<-c("A","B","C","D","E","F","G")
data0<-data.frame(S, D_s)

This is the function of my mathematical model:

Instead of doing

data0<-data0 %>%
  mutate(
    Round1=((D_s*(1-1)/sum(D_s))),
    Round2=((D_s*(2-1)/sum(D_s))),
    Round3=((D_s*(3-1)/sum(D_s))),
    Round4=...
  )

I would guess there is a better way to do this, something in the form of (obviously not working, please don't judge):

for(k in 1:40){
data0<-data0 %>%
  mutate(Round_i=((D_s*(i-1))/sum(D_s))
}

Thanks in advance!

1 Answers

We can loop with map

library(purrr)
library(dplyr)
library(stringr)
map_dfc(1:3, ~ data0 %>%
                transmute(!! str_c("Round", .x) := ((D_s *(.x -1)/sum(D_s))))) %>%
    bind_cols(data0, .)
#  S D_s Round1     Round2    Round3
#1 A  34      0 0.13127413 0.2625483
#2 B  36      0 0.13899614 0.2779923
#3 C  27      0 0.10424710 0.2084942
#4 D  23      0 0.08880309 0.1776062
#5 E  30      0 0.11583012 0.2316602
#6 F  49      0 0.18918919 0.3783784
#7 G  60      0 0.23166023 0.4633205

It may be also better to create a function to do this as it is repeated task

f1 <- function(data, i) with(data, ((D_s*(i-1)/sum(D_s))))
data0[paste0("Round", 1:3)] <- lapply(1:3, f1, data = data0)
Related