小编Bri*_*n D的帖子

如何将几个大型data.table对象附加到单个data.table中并快速导出到csv而不会耗尽内存?

对此的简单回答是"购买更多内存",但我希望得到更具建设性的答案,并在此过程中学到一些东西.

我运行Windows 7 64位,内存为8GB.

我有几个非常大的.csv.gz文件(大约450MB未压缩),它们具有我读入R并执行一些处理的完全相同的标题信息.然后,我需要将处理过的R对象组合成一个主对象,并在磁盘上写回.csv.

我在多组文件上执行相同的操作.例如,我有5个文件夹,每个文件夹中包含6个csv.gz文件.我需要最终得到5个主文件,每个文件夹一个.

我的代码如下所示:

for( loop through folders ){
    master.file = data.table()

    for ( loop through files ) {
        filename = list.files( ... )
        file = as.data.table ( read.csv( gzfile( filename ), stringsAsFactors = F ))
        gc()

        ...do some processing to file...

        # append file to the running master.file
        if ( nrow(master.file) == 0 ) {
            master.file = file
        } else {
            master.file = rbindlist( list( master.file, file) )
        }
        rm( file, filename )
        gc()
    }

    write.csv( …
Run Code Online (Sandbox Code Playgroud)

memory csv r sqldf data.table

8
推荐指数
1
解决办法
1282
查看次数

如何从R中的线性模型中获得交叉验证的r-square?

我在R中有一个线性模型

set.seed(1234)
x <- rnorm(100)
z <- rnorm(100)
y <- rnorm(100, x+z)
mydata <- data.frame(x,y,z)

fit <- lm(y ~ x + z, mydata)
Run Code Online (Sandbox Code Playgroud)

我想获得样本r-square的估计值.我正在考虑使用某种形式的k-fold交叉验证.

  • R中的代码采用线性模型拟合并返回交叉验证的r平方?
  • 或者是否有其他方法可以使用R获得交叉验证的r-square?

r linear-regression cross-validation

7
推荐指数
1
解决办法
5991
查看次数

R - 如何通过光栅图像找到最低成本路径?

如何通过栅格图像数据找到非线性路径?例如,最低成本算法?起点和终点是已知的,并给出如下:

起点=(0,0)
终点=(12,-5)

例如,通过(灰度)光栅图像提取蜿蜒河流的近似路径.

# fake up some noisy, but reproducible, "winding river" data
set.seed(123)
df <- data.frame(x=seq(0,12,by=.01), 
                 y=sapply(seq(0,12,by=.01), FUN = function(i) 10*sin(i)+rnorm(1)))

# convert to "pixels" of raster data
# assumption: image color is greyscale, only need one numeric value, v
img <- data.frame(table(round(df$y,0), round(df$x,1)))
names(img) <- c("y","x","v")
img$y <- as.numeric(as.character(img$y))
img$x <- as.numeric(as.character(img$x))


## take a look at the fake "winding river" raster image...
library(ggplot2)
ggplot(img) +
  geom_raster(aes(x=x,y=y,fill=v))
Run Code Online (Sandbox Code Playgroud)

输出图像来自ggplot命令

r raster path-finding

5
推荐指数
1
解决办法
329
查看次数

如何在 geom_sf() 中翻转 y 轴?

试图将 ageom_sf()与其他一些几何体结合起来。我需要反转 y 轴以使绘图正确显示。然而,geom_sf()似乎忽略了scale_y_reverse()

例子:

# install the dev version of ggplot2
devtools::install_github("tidyverse/ggplot2")

library(ggplot2)
library(sf)
library(rgeos)
library(sp)

# make triangle
tmpdf <- data.frame(id = 1,
                    geom = c("LINESTRING(10 10,-10 10,0 0,10 10)"), stringsAsFactors = F)


# read WKT polygons into 'sp' SpatialPolygons object
tmpdf$spgeom <- lapply(tmpdf$geom, FUN = function(x) readWKT(x))

# extract coordinates from the linestring (there has got to be a better way to do this...)
test <- tmpdf[1,"spgeom"]
test2 <- sapply(test, FUN=function(x) …
Run Code Online (Sandbox Code Playgroud)

r ggplot2 r-sf

5
推荐指数
1
解决办法
1192
查看次数