Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

r - Turn extraction list to csv file

I have uploaded a raster file and polyline shapefile into R and use the extract function to to extract the data from every pixel along the polyline. How do I turn the list output by extract into a CSV file?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Always include a simple self-contained reproducible example (this one is taken from ?raster::extract

library(raster)
r <- raster(ncol=36, nrow=18, vals=1:(18*36))
cds1 <- rbind(c(-50,0), c(0,60), c(40,5), c(15,-45), c(-10,-25))
cds2 <- rbind(c(80,20), c(140,60), c(160,0), c(140,-55))
lines <- spLines(cds1, cds2)
e <- extract(r, lines)

e is a list

> e
[[1]]
 [1] 126 127 161 162 163 164 196 197 200 201 231 232 237 266 267 273 274 302 310 311 338 346 381 382 414 417 450 451 452 453 487 488

[[2]]
 [1] 139 140 141 174 175 177 208 209 210 213 243 244 249 250 279 286 322 358 359 394 429 430 465 501 537

and you cannot directly write this to a csv because the list elements (vectors) have different lengths.

So first make them all the same length

x <- max(sapply(e, length))
ee <- sapply(e, `length<-`, x)

Let's see

head(ee)
#     [,1] [,2]
#[1,]  126  139
#[2,]  127  140
#[3,]  161  141
#[4,]  162  174
#[5,]  163  175
#[6,]  164  177
tail(ee)
#      [,1] [,2]
#[27,]  450   NA
#[28,]  451   NA
#[29,]  452   NA
#[30,]  453   NA
#[31,]  487   NA
#[32,]  488   NA

And now you can write to a csv file

write.csv(ee, "test.csv", row.names=FALSE)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...