MockCommunity1
MockCommunity1

Reputation: 31

How to generate a sequence based on two columns in R?

Below you can recreate my data in R. I would like to generate a sequence of numbers based on two individual columns. In this example of real data my column names are :

df= or10x1BC

"Tank" "Core" "BCl"  "BCu"  "Mid"  "TL"   "SL"

I wish to use the value in each row from BCu and BCl to generate a sequence by 0.001. For example seq(BCu[1], BCl[1], 0.001) will generate a sequence based on the first row in each, I wish to have this work for each row down the list.

Ultimately this sequence will be used in my function to make an average of the sequence, i.e. mean(function(seq(Bcu[i], BCl[j], 0.001)) and be added to a new column or10x1BC["meanBVF"] = mean(function(seq(Bcu[i], BCl[j], 0.001)).

See data below:


structure(list(Tank = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L), .Label = "1", class = "factor"), Core = structure(c(1L, 
1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), .Label = c("A", "B", "C"), class = "factor"), 
    BCl = structure(c(8L, 5L, 2L, 6L, 3L, 1L, 9L, 7L, 4L), .Label = c("17", 
    "18", "22", "22.3", "23", "26", "27.3", "28", "29"), class = "factor"), 
    BCu = structure(c(8L, 5L, 2L, 6L, 3L, 1L, 9L, 7L, 4L), .Label = c("12.5", 
    "13.5", "17", "17.8", "18", "22", "22.3", "23", "27.3"), class = "factor"), 
    Mid = structure(c(8L, 5L, 2L, 6L, 3L, 1L, 9L, 7L, 4L), .Label = c("14.75", 
    "15.75", "19.5", "20.05", "20.5", "24", "24.8", "25.5", "28.15"
    ), class = "factor"), TL = structure(c(2L, 2L, 2L, 1L, 1L, 
    1L, 3L, 3L, 3L), .Label = c("26", "28", "29"), class = "factor"), 
    SL = structure(c(4L, 4L, 3L, 2L, 4L, 3L, 1L, 4L, 3L), .Label = c("1.7", 
    "4", "4.5", "5"), class = "factor")), .Names = c("Tank", 
"Core", "BCl", "BCu", "Mid", "TL", "SL"), row.names = c(NA, -9L
), class = "data.frame")

Upvotes: 0

Views: 2526

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 146224

mapply is like apply, or lapply, but with multiple arguments:

First, as I mentioned in the comment, we need to convert your data to numeric. I did it like this, to convert all but the second column:

df[, -2] = lapply(df[, -2], as.character)
df[, -2] = lapply(df[, -2], as.numeric)

We can then use mapply like this to generate the sequences:

seqs = mapply(FUN = function(a, b) {
      seq(from = a, to = b, by = .001)
  }, a = df$BCu, b = df$BCl)

It seems messy to put that in the data frame, but you can if you'd like:

df$seqs = seqs

If it were me, I'd probably leave it as a list of vectors outside of the data frame.

Upvotes: 1

Related Questions