Creating a loop in r
![creating a loop in r creating a loop in r](https://statisticsglobe.com/wp-content/uploads/2020/09/for-Loop-Index-in-R-Feature-Image.png)
![creating a loop in r creating a loop in r](https://i.stack.imgur.com/jY5Hj.jpg)
If(is.numeric(fau_dat)) fau_dat<-ifelse(is.na(fau_dat), Lets combine with an if function to prevent filling in of non-numeric columns but first, lets restore the original dataframe Note that the function returns 1 value either TRUE or FALSE. Woa, what just happened? All the letters turned to numbers maybe we should restrict the filling-in to just numeric columns. We know how use for loops and bracket notation to accomplish this task but first we need to find out how many column are in the dataframe.įau_dat<-ifelse(is.na(fau_dat),mean(fau_dat, na.rm = T),fau_dat) If we want to apply the function to another object, we will have to make it generic enough to apply to any dataframe. So lets start by creating code that replaces missing values, recall from the ifelse lesson.įau_dat$Num<-ifelse(is.na(fau_dat$Num1),mean(fau_dat$Num1, na.rm = T),fau_dat$Num1) # now assign missing values to a few placesįau_dat<-fau_dat<-fau_dat<- NAĪll function creation usually starts with creating the code for doing the work, then we make the code generic so we can use it with other objects, the last thing we do is turn the code into a function. #' first create a dataframe with fake data lets call it fau_datįau_dat Ok all of that is fine and good why would you want to bother learning how to create a function? Lets make something that you might actually use, like finding and replacing NA with mean values. The above demonstrates the usefulness of functions and the idea that the order of the inputs matters.Creating a loop in r how to#