Line by line math in a data set

I have a data set of surveys and I am trying to calculate row by row. The new output column should be based on data from that row. I can make the new row and do that math, but the result is applied to all rows.

How do I get the math output column to match the math on a row by row basis? My code is below, and it works for calculating the surveys in the new column correctly. The trouble is, it calculates for all rows instead of just row 2.

tvd <- function(depth, inclination) {
  tvd <- cos(inclination * pi / 180) * depth
  print(tvd)
}

surveys_1 <- surveys

surveys_1$TVD <- tvd(surveys_1[2,1], surveys_1[2,2])

head(surveys_1)

Does anyone know how to fix this?

Why did you choose to calculate for row 2 ? Just remove that...

Do you mean remove the [2,1] and [2,2]?

I have several hundred rows and I want the math to calculate for each row individually. How do I specify the rows without the hard bracket notation?

surveys_1$TVD <- tvd(surveys_1[,1], surveys_1[,2])

Is the way.

If you want to avoid base R Square brackets notation you could study tidyverse approaches.

Particularly chapter 5

OK thank you. I will review that chapter in r4ds.

Yes, this is prettier:

surveys_1 %>%
  mutate(TVD = tvd(depth, inclination))

But now the math is all wonky. I need to go back and adjust my function.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.