I have a list which includes 2 data.frames
(i.e. text
files) and would like to apply some analysis on them . I performed my analysis to a single data.drame
but I want to do the same (analysis) over my list. I am a bit confused on how to do that. My code for the single data.frame
is below:
setwd("mydir")
#import .txt file
d = read.table("vourlionas.txt",
header = FALSE,
sep="",
col.names=c("x", "y"),
fill=FALSE,
strip.white=TRUE,
stringsAsFactors = FALSE)
#remove the 1st row of the .txt file
d2 = d[-1,]
d3 = substr(d2$x, 1, 6)
d4 = substr(d2$y, 1, 7)
df <- cbind(d3, d4)
df1 <- as.data.frame(df)
b = apply(as.matrix(df1),2,as.character)
#rename the column names of the matrix
colnames(b) [1] = paste("x")
mode(b) = "numeric"
b2 <- as.data.frame(b)
ch <- chull(b2)
coords <- b2[c(ch, ch[1]), ]
sp_poly <- SpatialPolygons(list(Polygons(list(Polygon(coords)), ID=1)))
proj4string(sp_poly) <- CRS("+init=epsg:2100")
sp_poly_df <- SpatialPolygonsDataFrame(sp_poly, data=data.frame(ID=1))
test1 = spTransform(sp_poly_df, "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
writeOGR(obj=test1, dsn="mydir", layer = "r"
driver="ESRI Shapefile", overwrite_layer = TRUE)
When I try to create a function
and pass it over the list, instead of getting 2 shapefiles
I am getting only one:
library(dplyr)
library(purrr)
library(tibble)
library(sp)
#Get list of files
mydir="C:/path/to/textfiles/"
temp = list.files(mydir,pattern="*.txt$",full.names = TRUE)
fn = list.files(mydir,pattern="*.txt$")
temp=enframe(temp)%>%
mutate(savedir=fn)
temp = temp %>%
#load in your table
mutate(data = map(value,~read.table(.,header = FALSE,
sep="",
col.names=c("x", "y"),
fill=FALSE,
strip.white=TRUE,
stringsAsFactors = FALSE)))
#Your function
myfunction = function(temp,save_name){
#remove the 1st row of the .txt file
d2 = temp[-1,]
d3 = substr(d2$x, 1, 6)
d4 = substr(d2$y, 1, 7)
df <- cbind(d3, d4)
df1 <- as.data.frame(df)
b = apply(as.matrix(df1),2,as.character)
#rename the column names of the matrix
colnames(b) [1] = paste("x")
mode(b) = "numeric"
b2 <- as.data.frame(b)
ch <- chull(b2)
coords <- b2[c(ch, ch[1]), ]
sp_poly <- SpatialPolygons(list(Polygons(list(Polygon(coords)), ID=1)))
proj4string(sp_poly) <- CRS("+init=epsg:2100")
sp_poly_df <- SpatialPolygonsDataFrame(sp_poly, data=data.frame(ID=1))
test1 = spTransform(sp_poly_df, "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
writeOGR(obj=test1, dsn="mydir", layer = "r",
driver="ESRI Shapefile", overwrite_layer = TRUE)
}
map2(temp$data,temp$savedir,~myfunction(.x,.y))
Any thoughts? I have posted the same question here, but the answer I have got was incorrect.