user2299914
user2299914

Reputation: 111

apply function multiple dataframes in R

I have multiple data frames and would like to take the same action across an identically named column in each data frame.

I was able to do a for loop to read the multiple CSVs and create the dataframes but couldn't get a for loop to work to use str_pad across the same column in dataframes.

For example, I have:

a$ARTICLE_NUMBER <- str_pad(a$ARTICLE_NUMBER, 11, pad = 0)
b$ARTICLE_NUMBER <- str_pad(b$ARTICLE_NUMBER, 11, pad = 0)
c$ARTICLE_NUMBER <- str_pad(c$ARTICLE_NUMBER, 11, pad = 0)

I've tried:

vendor_list <- c("a", "b", "c")

for(i in vendor_list){
  i[ARTICLE_NUMBER] <- str_pad(i[ARTICLE_NUMBER], width = 11, pad = 0)
}

As well as:

lapply(vendor_list, function(x){
  x[ARTICLE_NUMBER] <- str_pad(x[ARTICLE_NUMBER], width = 11, pad = 0)
  return(x)
})

Also:

string_pad <- function(x){
  x[ARTICLE_NUMBER] <- str_pad(x[ARTICLE_NUMBER], width = 11, pad = 0)
}

vendor_list <- lapply(vendor_list, string_pad(x) x[, 1])

Not sure what I'm missing. Any help is much appreciated!

Upvotes: 3

Views: 4954

Answers (3)

Onyambu
Onyambu

Reputation: 79338

I see some few errors here and there: What is a$ARTICLE_NUMBER that need to be passed as an argument into the function str_pad?? is it already existing while running the for loop/ lapply function?? If yes then you have to be able to write the lapply/for loop function. Since I do not know how your data looks like, I would you a simpler version here

Define your variables as:

    a=b=c=list()# Just ensure they are lists

   lapply(list(a=a,b=b,c=c),function(x) {x$ARTICLE_NUMBER= "TYPE FUNCTION HERE";x})

From the above code I get the results:

$a
$a$ARTICLE_NUMBER
[1] "TYPE FUNCTION HERE"


$b
$b$ARTICLE_NUMBER
[1] "TYPE FUNCTION HERE"


$c
$c$ARTICLE_NUMBER
[1] "TYPE FUNCTION HERE"

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522741

You could add the three data frames to a list and then use lapply():

df_list <- list(a, b, c)
lapply(df_list, function(x) {
    x[["ARTICLE_NUMBER"]] <- str_pad(x[["ARTICLE_NUMBER"]], 11, pad = 0)
})

Upvotes: 1

jameselmore
jameselmore

Reputation: 442

I think the primary issue was the manor in which you were addressing the column in the data.frame, your first attempt would work for something like this:

i[['ARTICLE_NUMBER']] <- str_pad(i[['ARTICLE_NUMBER']], width = 11, pad = 0)

In either case, I recommend a different approach. Operations like this on data.frames are much easier in the dplyr package

library(dplyr)

vendor_list <- list(a, b, c)
pad_article_num <- 
    function(df) {
         mutate(df, ARTICLE_NUMBER = str_pad(ARTICLE_NUMBER, width = 11, pad = 0)
    }
vendor_list <- lapply(vendor_list, pad_article_num)

Upvotes: 2

Related Questions