为家庭作业编写代码。代码运行良好,但是当我尝试该函数时,我收到了这个 #'ed 错误(我不明白)。该代码应该采用坐标数据框,保留坐标,并添加表示坐标所属半球的列。所以问题是如何更改函数/代码以消除错误?
此外,该代码使用包 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
这是输出应该是什么(在设置种子和 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)
}