so_newmember
so_newmember

Reputation: 13

Extract rows from csv files in R

I want to extract lat/long data + file name from csv

I have done the following:

#libraries-----
library(readr)
library("dplyr")
library("tidyverse")


# set wd-----EXAMPLE
setwd("F:/mydata/myfiles/allcsv")

# have R read files as list -----
list <- list.files("F:/mydata/myfiles/allcsv", pattern=NULL, all.files=FALSE,
                  full.names=FALSE)
list
]

#lapply function
row.names<- c("Date=0", "Time=3", "Type=2", "Model=1", "Coordinates=nextrow", "Latitude = 38.3356", "Longitude = 51.3323")
AllData <- lapply(list, read.table, 
                  skip=5, header=FALSE, sep=";", row.names=row.names, col.names=NULL)

PulledRows <- 
  lapply(AllData, function(DF) 
    DF[fileone$Latitude==38.3356, fileone$Longitude==51.3323]
  )

# maybe i need to specify a for loop?

how my data looks

Thank you.

Upvotes: 1

Views: 1317

Answers (1)

ErrorJordan
ErrorJordan

Reputation: 641

This should work for you. You may have to change the path location if the .csv files are not in your working directory. And the location to save the final results.

results <- data.frame(Latitude=NA,Longitude=NA,FileName=NA) #create empty dataframe
for(i in 1:length(list)){ # loop through each file obtained from list (called above)
  dat <- read_csv(list[i],col_names = FALSE) # read in the ith dataset
  df <- data.frame(dat[6,1],dat[7,1],list[i]) # create new dataframe with values from dat
  df[,1] <- as.numeric(str_remove(df[,1],'Latitude=')) # remove text and make numeric
  df[,2] <- as.numeric(str_remove(df[,2],'Longitude='))
  names(df) <- names(results) # having the same column names allows next line
  results <- rbind(results,df) # 'stacks' the results dataframe and df dataframe
}
results <- na.omit(results) # remove missing values (first row)
write_csv(results,'desired/path')

Upvotes: 1

Related Questions