Gambit
Gambit

Reputation: 233

How to create a function in R?

Instead of write the command one by one, such as :

data_101$new_column <- "a101" 
data_102$new_column <- "a102" 
data_103$new_column <- "a103" 
data_104$new_column <- "a104" 
data_105$new_column <- "a105"
...
data_150$new_column <- "a150"

How to write a function which can save the works? Here is my command (not sure correct or not because I am still new to R)

table_name <- "data_101"
for (i in 2:50) {
  temp <- paste("dat_10", i, sep = "")
  table_name<- c(table_name, temp)
}

But I don't know how to continue it already, I have tried my best...anyone can help me? Will be very appreciate it.

Upvotes: 0

Views: 84

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388807

You could use ls to get the objects and then mget to get data in a list. We can use Map to add a new column in each dataframe

d_names <- ls(pattern = 'data_\\d+')
total_data <- Map(cbind, mget(d_names), 
                  new_column = paste0("a", gsub("\\D", "", d_names)))

It is usually better to keep data in a list instead of creating lot of objects in the global environment but if you need them as separate dataframe you can use list2env.

list2env(total_data, .GlobalEnv)

Using a reproducible example :

data_101 <- data.frame(a = 1:5, b = 11:15)
data_102 <- data.frame(a = 6:10, b = 16:20)
d_names <- ls(pattern = 'data_\\d+')
Map(cbind, mget(d_names), new_column = paste0("a", gsub("\\D", "", d_names)))

#$data_101
#  a  b new_column
#1 1 11       a101
#2 2 12       a101
#3 3 13       a101
#4 4 14       a101
#5 5 15       a101

#$data_102
#   a  b new_column
#1  6 16       a102
#2  7 17       a102
#3  8 18       a102
#4  9 19       a102
#5 10 20       a102

Upvotes: 2

Kenny Tung
Kenny Tung

Reputation: 1

You can store the data frame within a list, so you can run the for-loop like:

data <- list()
for (i in c(105,106,...,150)){
    data[[i]]$new_column <- paste0("a",i)
}

Upvotes: 0

Related Questions