user1489719
user1489719

Reputation: 119

Dynamically Create Columns in R

I have a dataset for which I'd like to be able to dynamically create columns, including their names.

An example simplified dataset is:

dataset <- data.frame(data = c(0,1,2,3),
                      signups = c(100, 150, 200, 210),
                      leads = c(10, 12, 15, 18),
                      opportunities = c(2, 4, 5, 3), 
                      closed = c(1,4,2,1))

I'd like the following additional fields for the dataset, defined as such:

lead_percentage <- dataset$leads / dataset$signups
opportunity_percentage <- dataset$opportunities / dataset$signups
closed_percentage <- dataset$closed / dataset$signups

I have many columns for which this happens, and can't figure out how to loop through in order to do this.

So far, I know I can create a list of the column names using this code:

colnames_list <- 0
c <- 1
for(c in c(4:ncol(dataset)-1)) {
    colnames_list[c] = paste(colnames(dataset)[c], "percentage")
}

I also know how to dynamically define the values of the new columns, but can't seem to figure out how to get the new column names from the list to the dataframe.

Upvotes: 1

Views: 2939

Answers (1)

Andrea
Andrea

Reputation: 603

this could what you need

l <- lapply(dataset[,3:5], "/", dataset$signups)
names(l) <- paste(names(dataset[,3:5]), "percentage", sep = "_")
dataset <- cbind(dataset,l)

Upvotes: 2

Related Questions