宿題のコードを書いています。コードはうまくいきますが、関数を試してみると、この # 付きのエラーが表示されます (これはわかりません)。コードは、座標のデータフレームを取得し、座標を保持し、座標がどの半球の一部であるかを示す列を追加することになっています。問題は、関数/コードを変更してエラーを取り除く方法です。
また、コードはパッケージ sp および foreach を使用します。
データフレーム入力とエラー出力は次のとおりです。
set.seed(10)
n <- 10
df <- data.frame(xpos=runif(n,0,360),ypos=runif(n,-90,90))
df
outHemisphere <- hemisphereSummary(df=df)
outHemisphere
# Error in eval(expr, envir, enclos) : argument is missing, with no default
出力は次のようになります (seed と df がワークスペースに設定された後)。
outHemisphere <- hemisphereSummary(df=df)
outHemisphere
# coordinates EWhemisphere NShemisphere
#1 (182.692, 27.298) W N
#2 (110.437, 12.1928) E N
#3 (153.687, -69.5684) E S
#4 (249.517, 17.2666) W N
#5 (30.6489, -25.551) E S
#6 (81.1572, -12.8143) E S
#7 (98.831, -80.6574) E S
#8 (98.0298, -42.448) E S
#9 (221.699, -18.2177) W S
#10 (154.682, 60.5041) E N
エラーなしで入力する割り当てのコード/関数は次のとおりです。
hemisphereSummary <- function(df, projargs="+proj=longlat +datum=WGS84")
{
# install.packages("foreach")
# install.packages("sp")
library("foreach")
library("sp")
if(class(df)!="data.frame") stop ("df must be a data frame.")
registerDoSEQ() # register the non-parallel backend for foreach.
df_mat <- cbind(df[,1], df[,2]) #makes matrix of 2 cols, drawing from df.
row.names(df_mat) <- as.character(1:nrow(df_mat))
df_CRS <- CRS(projargs) # correct projection arguments.
df_sp <- SpatialPoints(coords=df_mat,proj4string=df_CRS) # makes spatial object!
# df_sp
foreachloop <- foreach(i = 1:(nrow(df)), .packages = "sp", .combine="rbind",) %dopar%
{
findhemisphere <- function(i, df_sp, df) # nested function to sort which hemi.
{
coords <- coordinates(df_sp[i,])
hemi_names <- df
colnames(hemi_names) <- c("EWhemisphere", "NShemisphere")
#if-else's: E=0-180, W=181-360. N=0 to +90, S=-1 to -90.
ifelse(coords[1] >=0 & coords[1] <=180,coords[1] <- "E", coords[1] <- "W")
ifelse(coords[2] >=0 & coords[2] <=90,coords[2] <- "N", coords[2] <- "S")
return(hemi_names)[i,] <- coords
}
}
SPdataframe <- SpatialPointsDataFrame(coords=coordinates(df_sp),
data = foreachloop, proj4string = df_CRS, match.ID = FALSE)
}