クエリを実行するポイントのデータが、x 座標と y 座標の data.frame と、クエリを実行するレイヤーの適切な種名で構成されている場合は、次の 2 つのコマンドを使用してすべてを実行できます。
# Find the layer to match on using 'grepl' and 'which' converting all names to lowercase for consistency
df$layer <- lapply( df$species , function(x) which( grepl( tolower(x) , tolower(names(s)) ) ) )
# Extract each value from the appropriate layer in the stack
df$Value <- sapply( seq_len(nrow(df)) , function(x) extract( s[[ df$layer[x] ]] , df[ x , 1:2 ] ) )
使い方
最初の行から始めます。
- 最初に、その行に使用する必要があるスタック内
df$layer
のインデックスとなる新しい列ベクトルを定義します。rasterLayer
lapply
列内のすべての要素に沿って反復し、入力変数として順番df$species
に各項目を使用して無名関数を適用します。ループ構成のようには見えませんが、これはループ構成です。df$species
x
lapply
df$species
最初の繰り返しで、 whichの最初の要素を取り、x
それを使用してgrepl
(「グローバル正規パターン マッチング論理」のようなものを意味します)、スタックの名前のどの要素にs
種パターンが含まれているかを見つけます。tolower()
( ) と一致するパターンと ( x
) で一致する要素の両方で使用しnames(s)
て、大文字と小文字が一致しない場合でも一致するようにし"Tiger"
ます"tiger"
。
grepl
は、パターンの一致を検出した要素の論理ベクトルをgrepl( "abc" , c("xyz", "wxy" , "acb" , "zxabcty" ) )
返します。たとえば、 returnF , F , T , T
です。which
これらの要素のインデックスを取得するために使用します。
- アイデアは、スタック内のレイヤーと各行の種名との一致を 1 つだけ取得することです。そのため、唯一
TRUE
のインデックスは、必要なスタック内のレイヤーのインデックスになります。
2 行目sapply
:
sapply
はイテレータとよく似lapply
ていますが、値のリストではなくベクトルを返します。TBH は、このユースケースでどちらでも使用できます。
1
ここで、 からまでの一連の数値を反復処理しnrow(df)
ます。
- 入力変数として別の無名関数の行番号を使用します
x
- 前の行で取得したレイヤーを使用して、data.frameの現在の行 ( で指定) の
"x"
と"y"
座標 (それぞれ列 1 と 2)を抽出します。x
x/y
これらすべてを実行した結果を、適切なレイヤーのその座標に対して抽出された値を含む data.frame の別の列に割り当てます
それが役立つことを願っています!!
そして、いくつかのデータを使用した実際の例:
require( raster )
# Sample rasters - note the scale of values in each layer
# Tens
r1 <- raster( matrix( sample(1:10,100,repl=TRUE) , ncol = 10 ) )
# Hundreds
r2 <- raster( matrix( sample(1e2:1.1e2,100,repl=TRUE) , ncol = 10 ) )
# Thousands
r3 <- raster( matrix( sample(1e3:1.1e3,100,repl=TRUE) , ncol = 10 ) )
# Stack the rasters
s <- stack( r1,r2,r3 )
# Name the layers in the stack
names(s) <- c("LIon_medIan" , "PANTHeR_MEAN_AVG" , "tiger.Mean.JULY_2012")
# Data of points to query on
df <- data.frame( x = runif(10) , y = runif(10) , species = sample( c("lion" , "panther" , "Tiger" ) , 10 , repl = TRUE ) )
# Run the previous code
df$layer <- lapply( df$species , function(x) which( grepl( tolower(x) , tolower(names(s)) ) ) )
df$Value <- sapply( seq_len(nrow(df)) , function(x) extract( s[[ df$layer[x] ]] , df[ x , 1:2 ] ) )
# And the result (note the scale of Values is consistent with the scale of values in each rasterLayer in the stack)
df
# x y species layer Value
#1 0.4827577 0.7517476 lion 1 1
#2 0.8590993 0.9929104 lion 1 3
#3 0.8987446 0.4465397 tiger 3 1084
#4 0.5935572 0.6591223 panther 2 107
#5 0.6382287 0.1579990 panther 2 103
#6 0.7957626 0.7931233 lion 1 4
#7 0.2836228 0.3689158 tiger 3 1076
#8 0.5213569 0.7156062 lion 1 3
#9 0.6828245 0.1352709 panther 2 103
#10 0.7030304 0.8049597 panther 2 105