edquant / edh7916

Course materials and website for EDH7916: Contemporary Research in Higher Education
https://edquant.github.io/edh7916/
3 stars 1 forks source link

Syntax for Functions used in Loops... #38

Closed nszekeres closed 2 years ago

nszekeres commented 4 years ago

Hi, Dr. Skinner - I see I'm not getting this. :( When I see the functions, I'm not understanding how to apply the function to a particular domain -- data frame, column, etc. Like, in Q2: The point is to use an existing fuction. Are we supposed to pipe in the data and select out the variable so R knows to what variable apply the function toward?

I tried this:

#Using the user-written function fix_missing(), convert missing values in x1ses to NA:

df_q2 %>%
  select(x1ses) %>%
  fix_missing <- function(x, miss_val) {
  ## use ifelse(< test >, < do this if TRUE >, < do that if FALSE >)
  x <- ifelse(x %in% miss_val, # is x == any value in miss_val?
              NA, # TRUE: replace with NA
              x) # FALSE: return original value as is
  ## return corrected x
  return(x)
}

And I got this error message:

Error in df_q2 %>% select(x1ses) %>% fix_missing <- function(x, miss_val) { : 
  could not find function "%>%<-"

Thanks, Naomi

btskinner commented 4 years ago

@nszekeres: right now, you are trying to define the function within the dplyr chain. While there are ways to do that, you don't need to here. Instead, in sequence:

  1. define your function: fix_missing()
  2. read in the data
  3. convert missing values of x1ses to NA using your function fix_missing()

You can chain (2) and (3) together. So that your changes persist, you should assign the output to an object (like df). Also, you don't need to select() in order to mutate() the missing values to NA. Take another look at the first practical example in lesson 9.

btskinner commented 2 years ago

Closing since it's older.