0

I have written a function that loops over string data-frames. It takes the first string value of a df, does a calculation and proceed to the other row.

The arguments of the function are already in my workplace. When running the separate line of the function, it works perfectly. When trying to call it by giving the arguments, I get error message

value for ‘dtraw.id’ not found

Here is the function

test <- function(ids,dfs,columns){
  #dfs <- ls()[sapply(mget(ls(), .GlobalEnv), is.data.frame)]
  main_table<-merge(ids,mget(dfs[1])[[dfs[1]]],by='id',all.x=T)
  coln<-colnames(main_table) %in% columns
  main_table<-main_table[,coln]
  main_table[,dfs[1]]=rowSums(main_table[sapply(main_table,is.numeric)],na.rm = T)

  for(j in 2:length(dfs)){
    result<-as.data.frame(mget(dfs[j])[[dfs[j]]])
    coln<-colnames(result) %in% columns
    result<-result[,coln]
    result[,dfs[j]]<-rowSums(result[sapply( result,is.numeric)],na.rm = T)
    main_table<-merge(main_table,result[,c('id',dfs[j])],by='id',all.x=T)
  }
  saveRDS(main_table,'aggregates.rds')
  #return(main_table)
}

when calling test(ids,dfs,columns) I receive the error.

Any help what could be the reason?

esem
  • 153
  • 1
  • 12
  • You need to provide sample data so others can help. See more here [How to make a great R reproducible example?](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Tung May 04 '18 at 17:39

1 Answers1

0

You can use the get() function to pass it a dataframe name as a string. Otherwise R has no idea what you are trying to do.

df = data.frame('var1' = 1:100)

You can see the progression here of what works and doesnt:

summary(df)
summary('df')
summary(get('df'))
Nate Thompson
  • 625
  • 1
  • 7
  • 22