2

Background

Sorry if this is a repeat, I couldn't find an exact match to this question. So as part of a larger function, I'm trying to add a new column in a data.frame which is basically the division of two variables within that data.frame.

For example:

data(iris)

iris_test <- function(dataset, var1, var2) {
  data <- dataset
  data$length_width <- data$var1/data$var2
  return(data)
}

If i then utilize this function

iris <- iris_test(iris, 'Petal.Length', 'Petal.Width')

I would hopefully generate a new column with data$length_width, however the code is breaking.

 Error in `$<-.data.frame`(`*tmp*`, "length_width", value = numeric(0)) : 
  replacement has 0 rows, data has 150 

I suspect you could do something fancy with paste() or formula() but really I want to understand what is happening and wy.

PyPer User
  • 259
  • 1
  • 2
  • 8

1 Answers1

2

You cannot use character variables for the dollar notation. Try this:

data(iris)

iris_test <- function(dataset, var1, var2) {
  data <- dataset
  data$length_width <- data[[var1]]/data[[var2]]
  return(data)
}
Mike Wise
  • 22,131
  • 8
  • 81
  • 104