0

i really hope someone can help me on this. I have 40 excel files with data. Each of these files contain several data columns, and i have to take only 2 of them. While "reading" these files to bring them in R as data frames, i have to name them as "client" and a number (e.g. client1, client2, etc.) and possibly to add in each of them a column with values taken from a list i already have in R, called p, that should be named as Pasqua in the data frames. I wrote this code

for (e in seq(1:40)){
    assign(paste0("client",e),read_excel(paste("C:/Users/Windows 10/Desktop/DS/",e,".xlsx",sep=""),
col_types = c("skip", "numeric", "skip", "numeric", "skip", "skip", "skip","skip", "skip")))}

This works, and i then have 40 data frames as wished.

But if i try to insert in the loop the code to append the column i face several errors: i tried in this way

paste0("client",e,"[,Pasqua]")<-p

I have error target of assignment expands to non-language object since it seems R is not capable to handle assignments, with name of variables "built" in this way

then also in this way

df[,"Pasqua"]<-p

i have this error object of type 'closure' is not subsettable

Searching here on other users' posts i understand that a way can be using lapply() but i haven't found a way to use it properly. Can someone explain me how to handle this? Thank you in advance

  • [Don't ever create `d1` `d2` `d3`, ..., `dn` in the first place. Create a **list** `d` with `n` elements.](https://stackoverflow.com/a/24376207/1422451) – Parfait Apr 27 '20 at 20:48
  • Thank you, that opened me a "world".... – moltoy0 Apr 29 '20 at 08:40

1 Answers1

0

This should do the job:

# data
client3 <- client2 <- client1 <- data.frame(col1 = 1:3, col2 = 1:3)
p <- 4:6

# assigning new column to each df
for (e in 1:3) {
  eval(parse(text = paste0('client', e, '[,"Pasqua"] <- p')))
}
Piotr K
  • 859
  • 7
  • 18