Eric Green
Eric Green

Reputation: 7735

writing a function to extract a value from a dataframe

I'm trying to write my first function. The purpose of the function is to extract a value associated with a specific string. Here's my data:

mydata <- data.frame(varname=c("Item 1", "Item 2"),
                     value=c(4.452, 5.546))

My non-user-defined function approach is:

test.nofun <- round(mydata$value[mydata$varname=="Item 1"], 2)
test.nofun
# [1] 4.45

Here's the function I tried:

myfun <- function(dat, itemcol, valcol, item, rd) {
  x <- round(dat$valcol[dat$itemcol==item], rd)
}

test.fun <- myfun(mydata, varname, value, "Item 1", 2)
  1. The function does not work ("non-numeric argument to mathematical function").
  2. I don't think I am using the correct assignment approach to get the internal function object x to become test.fun.

Use case: Writing a paper that will reference values from summary dataframes. Something like, "The value of the first item, a very important construct, is \Sexpr{test.fun}." I know I can calculate summary stats inline, but in this particular use case, I need to be able to reference a cell value from an existing dataframe. Also, I do not want to specify row index values because "Item 1" might not aways be in the first row. Just happens to be in this simple example.

Upvotes: 0

Views: 77

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193677

In general, use [ instead of $ when trying to write a function.

We want to recreate (sans round):

mydata[, "value"][mydata[, "varname"] == "Item 1"]
# [1] 4.452

And this is how we would do that:

myfun <- function(dat, itemcol, valcol, item, rd) {
  round(dat[, valcol][dat[, itemcol] == item], rd)
}

You'll also need to quote most of the arguments (unless you add a few lines to your function).

myfun(mydata, "varname", "value", "Item 1", 2)
# [1] 4.45

Upvotes: 2

Related Questions