1

HI i just started learning R and finding this problem to be really interesting where I just run a code directly without wrapping in a function it works but when I place it inside a function it doesn't work, What can be possible reason?

fill_column<-function(colName){

count <- 0

for(i in fg_data$particulars) {
count <- count +1

if(grepl(colName, i) && fg_data$value[count] > 0.0){
  fg_data[,colName][count] <- as.numeric(fg_data$value[count])

} else {
  fg_data[,colName][count] <- 'NA'
  }
 }
}

fill_column('volume')

Where I am creating new column named volume it this string exists in particulars column.

I have added a comment where solution given by another question does not work for me, Please look at my comment below.

Anand Sharma
  • 47
  • 1
  • 6
  • try adding `fg_data` just before closing curly bracket of the function fill_column – Imran Ali Nov 28 '16 at 03:25
  • Thanks for the answer, I tried that but it did the same things. Any other suggestion? – Anand Sharma Nov 29 '16 at 01:09
  • It would be easier to answer your question, if you could share first few rows of your dataframe – Imran Ali Nov 29 '16 at 08:33
  • Sure here it is https://drive.google.com/file/d/0B3ija2dBXuVbVkVzdDFIWENoUHM/view?usp=sharing – Anand Sharma Nov 30 '16 at 00:50
  • Possible duplicate of [Update data frame via function doesn't work](http://stackoverflow.com/questions/3969852/update-data-frame-via-function-doesnt-work) – Imran Ali Nov 30 '16 at 02:06
  • Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). This will make it much easier for others to help you. – zx8754 Nov 30 '16 at 07:33

1 Answers1

1

Finally I got it working but reading another answer on SO, here is the solution:

fill_column <- function(colName){

  count <- 0

 for(i in fg_data$particulars) {
   count <- count +1

    if(grepl(colName, i) && fg_data$value[count] > 0.0){
     fg_data[,colName][count] <- as.numeric(fg_data$value[count])

    } else {
      fg_data[,colName][count] <- 'NA'
   }
 }
 return(fg_data)
}

fg_data = fill_column('volume')

Now reason, Usually in any language when we modify global object inside any function it reflects on global object immediately but in R we have to return the modified object from function and then assign it again to global object to see our changes. or another way for doing this is to assign local object from within the function to global context using envir=.GlobalEnv.

Community
  • 1
  • 1
Anand Sharma
  • 47
  • 1
  • 6
  • Its getting interesting now. When I execute the code now it reports Error in `[.data.frame`(`*tmp*`, , colName) : undefined columns selected Called from: `[.data.frame`(`*tmp*`, , colName) although earlier it has working fine. Anyone else has faced this issue? – Anand Sharma Dec 01 '16 at 01:32