'for' loop on columns with multiple numbers in name, R

时间:2017-06-15 10:00:28

标签: r loops for-loop numbers overwrite

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!

1 个答案:

答案 0 :(得分:1)

不要试图找出新列的整数索引,而只需使用df[["string"]]语法命名列。

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)]
      )
  }
}