G78
G78

Reputation: 1

using value of a function & nested function in R

I wrote a function in R - called "filtre": it takes a dataframe, and for each line it says whether it should go in say bin 1 or 2. At the end, we have two data frames that sum up to the original input, and corresponding respectively to all lines thrown in either bin 1 or 2. These two sets of bin 1 and 2 are referred to as filtre1 and filtre2. For convenience the values of filtre1 and filtre2 are calculated but not returned, because it is an intermediary thing in a bigger process (plus they are quite big data frame). I have the following issue:

(i) When I later on want to use filtre1 (or filtre2), they simply don't show up... like if their value was stuck within the function, and would not be recognised elsewhere - which would oblige me to copy the whole function every time I feel like using it - quite painful and heavy.

I suspect this is a rather simple thing, but I did search on the web and did not find the answer really (I was not sure of best key words). Sorry for any inconvenience. Thxs / g.

Upvotes: 0

Views: 162

Answers (1)

Jouni Helske
Jouni Helske

Reputation: 6477

It's pretty hard to know the optimum way of achieve what you want as you do not provide proper example, but I'll give it a try. If your variables filtre1 and filtre2 are defined inside of your function and you do not return them, of course they do not show up on your environment. But you could just return the classification and make filtre1 and filtre2 afterwards:

#example data
df<-data.frame(id=1:20,x=sample(1:20,20,replace=TRUE))

filtre<-function(df){
   #example function, this could of course be done by bins<-df$x<10
  bins<-numeric(nrow(df))
  for(i in 1:nrow(df))
    if(df$x<10) 
      bins[i]<-1
  return(bins)
}

bins<-filtre(df)

filtre1<-df[bins==1,]
filtre2<-df[bins==0,]

Upvotes: 1

Related Questions