从R中的csv文件中提取行

时间:2019-12-09 17:51:49

标签: r

我想从csv中提取经纬度数据和文件名

我已经执行以下操作:

#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

谢谢。

1 个答案:

答案 0 :(得分:1)

这应该为您工作。如果.csv文件不在您的工作目录中,则可能必须更改路径位置。以及保存最终结果的位置。

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')