0

This question has sort of been asked multiple times, including in this example: Lapply to Add Columns to Each Dataframe in a List.

However, I simply want to add an argument within a function that creates a new column, and that column has a value based on input.

dfs<-lapply(clients_names, function(x){

df<-read.csv(...),

##this is when I want to add a column to the df loaded,
##a column of clients with names their names)

return(df)
})

I tried using df$clients<- x in place of ## but that did not work.

UPDATE:

client_names<-c("Bob", "Sam", "Chris")
Community
  • 1
  • 1
sammyramz
  • 533
  • 2
  • 5
  • 13
  • Since your basic premise of `df$clients <- x` is fine, it must be something else. Can you show more code that indicates how you make `x`? – r2evans Jun 23 '16 at 22:45
  • What error does it give you? – r2evans Jun 23 '16 at 22:49
  • error in `$<-.data.frame`(`*temp*`, "column", value = "Bob"): replacement has 1 row, data has 0. – sammyramz Jun 23 '16 at 22:51
  • 1
    This error means that `df` is empty, so your problem is elsewhere. (Try `df <- data.frame(a=1,b=2)[0,] ; df ; df$c <- 3` for a simple reproduction.) – r2evans Jun 23 '16 at 22:54
  • 1
    I don't know. Some debugging might be in order. To find out which of your `client_names` is showing the problem, you might want to add `message(x)` as the first line in your function, then run it. If the name that shows the problem is not the first one in the vector, then add something like `if (x == "Sam") browser()` so that you can easily get to the problem element in the list. Either way, there's not much I can do here without having all of your files (not asking) or seeing more code and sample data. – r2evans Jun 23 '16 at 23:27
  • Hey @r2evans. Thank you for your advice. After checking what you recommended, it worked since I found the bug! I initially doubted that function even though I used it before. Thanks! – sammyramz Jun 24 '16 at 05:32

0 Answers0