I am new to writing functions and I'm not really sure where to start. Below is a subset of a data frame named m1 for this example. I would like to write a function that will go through the data set and extract length and depth information by number. For instance, if it encounters the number 1 it takes the length and depth and inserts them into the first row of a new data frame or vectors. It then does the same if the number equals 2 and so on.
length number depth
[1,] 109 1 10
[2,] 109 1 10
[3,] 109 1 10
[4,] 109 1 10
[5,] 109 1 10
[6,] 109 1 10
[7,] 109 1 10
[8,] 109 1 10
[9,] 109 1 10
[10,] 109 1 10
[11,] 109 1 10
[12,] 109 1 10
[13,] 107 2 10
[14,] 107 2 10
[15,] 107 2 10
[16,] 107 2 10
[17,] 107 2 10
[18,] 107 2 10
[19,] 107 2 10
[20,] 107 2 10
Here is an attempt at writing a function to get the output described above if the number equals 1.
length.fun=function(x)
{
lengths=numeric()
depth=numeric()
if (x[2]==1)
{
lengths=x[1]
depth=x[3]
}
return(cbind(depth,lengths))
}
length.fun(m1)
However, all I get as an output is this:
length.fun(m1)
depth lengths
Any help is greatly appreciated. Thanks
class(m1)?data.framewith two rows, one fordepth, one forlengths. Or multiple rows, one for each unique element innumber. Or with multiple rows, two for each unique element innumber, one forlengths, one fordepth? Please be a bit more detailed.10 109,10 107, etc.