Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

How to center a variable in a function in R

$
0
0

This is a following question of this question.

In my function, I would like to:

  1. create a new data frame with no missing values
  2. center some variables (i.e., iv1 and iv2) and add them to a new data frame as well as add prefix "center_" to the centered variables. That is "centered_man""centered_woman"

But when I run the code below, I got an error message - Error in[.data.frame(dataset, , c(iv1, iv2, dv)) : object 'man' not found. Can you help me?


# create example data
testData <- data.frame(man = c(9, 8, 3, 4, NA, 8),         
                       woman = c(5, 4, NA, NA, 1, 1),
                       love = c(1, 2, 3, 4, 5, NA))


# define the function

polynomial <- function(iv1, iv2, dv, dataset){
  # create a new data frame with no missing values in iv1, iv2, and dv
  dataTemp <- na.omit(dataset[, c(iv1, iv2, dv)])

  # add the cetnered variables to the new data frame - dataTemp
  dataTemp[, centered_iv1] <- scale(dataTemp[, iv1], center = TRUE, scale = FALSE)
  dataTemp[, centered_iv2] <- scale(dataTemp[, iv2], center = TRUE, scale = FALSE)

  # define the formula
  formula <- substitute(dv ~ centered_iv1 + centered_iv2 + I(centered_iv1^2) + I(centered_iv1 * centered_iv2) + I(centered_iv2^2))

  # run the formula
  model <- lm(formula = formula, data = dataset)
  return(summary(model))
}

# use the function

polynomial(iv1 = man,
           iv2 = woman, 
           dv = love,
           dataset = testData)

Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>