在下面的代码中,dataframe offshore_Sites已经存在,包含了大约1000个记录。我正在构建一个函数,这样我就可以在所有其他数据文件中重用它。
数据从SQL Server获取。目前我只得到了offshore_Sites一个,但其他的将以同样的方式生产。
其思想是调用此函数,该函数的内部有一个switch语句,根据数据格式,我将执行不同的转换。对于offshore_Sites 1,我需要连接一些字段,如示例中所示。
myStringConn <- "Driver=SQL Server;Server=SQL-SPATIAL;Database=AreasProt;Trusted_Connection=True;"
conn <- odbcDriverConnect(myStringConn)
offshore_Sites <- sqlQuery(conn, "select * from Offshore_Sites")
formatDataFrame <- function(dataframe) {
switch(dataframe, "offshore_Sites" = {
offshore_sites <- as.data.table(offshore_Sites)
offshore_sites <- setnames(offshore_sites, 1:6, c("status","country","region","area","long","lat"))
offshore_sites <- unique(offshore_sites[, list(status,
country = paste(sort(unique(country)), collapse = ' & '),
region = paste(sort(unique(region)), collapse = ' & '),
area,
long,
lat), by = code])
})
}
formatDataFrame(offshore_Sites)但是,当我运行这个程序时,我会得到一个错误:
交换机中的错误(dataframe,offshore_Sites ={: EXPR必须是长度1的向量。
有人知道发生了什么吗?
发布于 2015-08-11 12:29:58
我今天得到了一些灵感,我发现问题出在哪里。函数需要两个变量,dataframe名称和dataframe本身。
myStringConn <- "Driver=SQL Server;Server=SQL-SPATIAL;Database=AreasProt;Trusted_Connection=True;"
conn <- odbcDriverConnect(myStringConn)
offshore_Sites <- sqlQuery(conn, "select * from Offshore_Sites")
formatDataFrame <- function(dataframe, dataframeName) {
switch(dataframeName, "offshore_Sites" = {
offshore_sites <- as.data.table(dataframe)
offshore_sites <- setnames(offshore_sites, 1:6, c("status","country","region","area","long","lat"))
offshore_sites <- unique(offshore_sites[, list(status,
country = paste(sort(unique(country)), collapse = ' & '),
region = paste(sort(unique(region)), collapse = ' & '),
area,
long,
lat), by = code])
})
}
formatDataFrame(offshore_Sites, "Offshore_Sites")(谢谢你的评论:)
https://stackoverflow.com/questions/31919173
复制相似问题