从列表中选择元素

时间:2018-10-01 19:15:24

标签: r list select

a <- list(One = "a", Two = 1, Three= c (4, 5, 6))

如何在此列表中选取第一和第三元素? 尝试过

[[1, 3]]
a[[1, 3]]
x(a[["One"],["Three"]])
x(a[["One","Three"]]) 

和其他变体...

1 个答案:

答案 0 :(得分:2)

我们可以按位置分组

function shift() {
  try{
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var as = ss.getActiveSheet();                     
    var ar = as.getActiveRange();
    var vals = ar.getValues();
    var r; //variable for rows

    for (r = 0; r < vals.length; r++){                                           // for each row, up to the last row (iterate over all rows from top to bottom)
      if((vals[r][0].indexOf("PO") != -1)||(vals[r][0].indexOf("P0") != -1)){    // if first column in each row contains "PO"
        var c; // variable for columns                                                    
        var cols = []; // array to store all data temporarily (will be uses to set new values later)
        for (c = 0; c < vals[r].length; c++){                                   // then iterate over each column(cell) in the row
          if(c == 0){                                                           // if it is the first row,
            cols[c+1] = vals[r][c];                                             // assign second index of the array with the PO value (to simulate a shift)
            cols[c] = "";                                                       // assign the first index of the array a blank string
          }
          else{                                                                 // if it is not the first row
            cols[c+1] = vals[r][c];                                             // assign each additional column value to the next index (+1) of the array
          }
        }
        for (c = 0; c < vals[r].length; c++){                                   // once the array is finished, loop through the columns again foreach row
          vals[r][c] = cols[c];                                                 // this time, assigning the new values to the corresponding array indices
        }
      }
    }
    ar.setValues(vals);                                                         // now, set the values that you reassinged to the array
  }
  catch(err){
    SpreadsheetApp.getUi().alert(err);
  }
}

如果处理命名列表,我们还可以按名称进行子集

a[c(1, 3)]
#$One
#[1] "a"

#$Three
#[1] 4 5 6