Search code examples
rvectorsubsetintegral

R: Trouble subsetting a vector for use with trapz function (pracma package)


Apologies if this is a really basic question, or if I'm not asking it right. This is my first time asking a question here, and I am a self-taught R user so there are some big gaps in my understanding.

So I am using library(pracma) to take the trapezoidal integrals for the following data frame:

df <- data.frame(
x=c(1,2,3),
y1=c(3,4,5),
y2=c(1,2,1))

I want to take the trapezoidal integrals of both y1 and y2, each with respect to x. My thought was that I would just do a very simple sapply with trapz as my function:

sapply(2:ncol(df), function(y) trapz(df[1], df[y]))

But this yields the error "Arguments 'x' and 'y' must be real or complex vectors."

Specifically, I get this same error when I take trapz(df[1], df[2]), but it works fine when I try trapz(df$x, df$y1). As far as I can tell, these are the exact same commands, so I can't figure out why only the first one is giving me an error.

Is there any way around this? Or alternatively, any way I can use sapply on the different columns without subsetting by column index?

EDIT: Thank you for the very prompt and helpful response! I knew about [[ subsetting a list, but for some reason it never occurred to me that you could use it for a data frame. I am equal parts grateful and embarrassed :,)


Solution

  • You should use [[ rather than [ when indexing the values in df columns

    > sapply(2:ncol(df), function(y) trapz(df[[1]], df[[y]]))
    [1] 8 3