This1GoesTo11
This1GoesTo11

Reputation: 3

How to create a function from the for loop below

So I've created the following in R that prints the row number and column name of values missing but is there a way to turn what i've coded into a function - this is likely redic easy but I am very new to this... if I were to create a function based off the code below where would I input the "function_name <-"

for (i in 1:nrow(airbnb)){
  rownum <- i
    #print(rownum)
  for (j in 1:ncol(airbnb)){
    colname <- names(airbnb[,j])
      #airbnb[i,j]
        if(is.na(airbnb[i,j])){
          print(paste("Row Number:",i))
          print(paste("Column Name:",colname))
        }
  }
}    

Upvotes: 0

Views: 25

Answers (1)

Matt
Matt

Reputation: 7385

I think this is what you're looking for:

You can name your function whatever you want, here it is called missing_func

You can replace the x to be more descriptive, so you can change all of the values for x to be df or dataframe or xyz:

missing_func <- function(x){
  for (i in 1:nrow(x)){
  rownum <- i
  #print(rownum)
  for (j in 1:ncol(x)){
    colname <- names(x[,j])
    #airbnb[i,j]
    if(is.na(x[i,j])){
      print(paste("Row Number:",i))
      print(paste("Column Name:",colname))
    }
  }
  }    
}

Now to call the function above, you just need to supply a value for x (or whatever you choose)

missing_func(airbnb)

Upvotes: 2

Related Questions