1

My problem is very simple but I cannot get it to work (despite searching)... I'm a newbie to R.

I have a dataframe with light measurements. Measurements below the canopy were taken along 4 transects, on 13 positions within each transect. Measurements above the canopy were taken once per transect.

df$below_position_1_transect_1
df$below_position_2_transect_1
# Et cetera with position 1:13 and transect 1:4

df$above_transect_1
df$above_transect_2
# Et cetera with transect 1:4

I want to perform a simple function on those columns and put the results in new columns which are correctly named. There should be a total of 13*4 new columns.

lightavailable <- function(below,above) {below / above * 100}

for (i in c(1:13)) {
  for (j in c(1:4)) {
    df[,i] <- lightavailable(
      below  = df[,paste0("below_position_",i,"_transect_",j)],
      above  = df[,paste0("above_transect_",j)]
      )
    colnames(df)[i] <- paste0("transmitted_transect_",j,"_position_",i)
  }
}

As a result, 13 new columns were added but only for transect 4, meaning that the results from transect 1 up to 3 were overwritten. I'm sure it has to do with writing everything to df[,i], but I'm not sure how to fix it.

How should the code be edited such that new columns are created for all combinations of transects and positions?

Thank you!

Eva
  • 13
  • 3
  • Can you share some sample data and show us that the intended result should look like. Have a look at this post for help: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Phil Jun 15 '17 at 10:39
  • Thank you Phil, I will make sure do so next time. The problem is already solved now. – Eva Jun 15 '17 at 12:23

1 Answers1

1

Rather than trying to figure out what integer index your new column will have, just name the column using the df[["string"]] syntax.

for (i in c(1:13)) {
  for (j in c(1:4)) {
        #---- new variable name -----------------------#
    df[[paste0("transmitted_transect_",j,"_position_",i)]] <- 
      lightavailable(
        below  = df[,paste0("below_position_",i,"_transect_",j)],
        above  = df[,paste0("above_transect_",j)]
      )
  }
}
Benjamin
  • 16,897
  • 6
  • 45
  • 65