R 从文件名定义对象
在R中有没有办法从文件名定义对象 我从许多具有相同结构的年度文件(每月一列,每天一行)导入数据。每个文件都按照此方案命名:“Station_YYYY.txt”,其中YYYY是一年中的数字(例如1985年)R 从文件名定义对象,r,R,在R中有没有办法从文件名定义对象 我从许多具有相同结构的年度文件(每月一列,每天一行)导入数据。每个文件都按照此方案命名:“Station_YYYY.txt”,其中YYYY是一年中的数字(例如1985年) 我必须合并这些数据集,因此在融合之前,我需要为“Station”添加一列,为“year”添加一列。如果我正确理解您的问题 你做的事情 a <- "Station_YYYY.txt" dat<-read.csv(a,OTHER OPTIONS) a另一种方法是做几个简单的循环 要使
我必须合并这些数据集,因此在融合之前,我需要为“Station”添加一列,为“year”添加一列。如果我正确理解您的问题 你做的事情
a <- "Station_YYYY.txt"
dat<-read.csv(a,OTHER OPTIONS)
a另一种方法是做几个简单的循环
要使以下内容正常工作,请确保您的本地环境为空,因为我们将搜索作为文件名的“\ux”
setwd('') # direct R to where the files are stored
rm(list=ls())
files <- list.files()
for(file in files){
name <- paste(file)
name <- assign(name, read.csv(file))
}
data_sets <- grep('_', ls(), value = T)
allData <- data.frame()
for(i in data_sets){
dat <- get(i)
station_end <- data.frame(str_locate(i, '_'))$start - 1
year_end <- data.frame(str_locate(i, '_'))$end + 4
dat$station <- str_sub(i, 1, station_end)
dat$year <- str_sub(i, station_end + 2, year_end)
allData <- rbind(allData, dat)
}
allData
setwd(“”)#将R指向文件存储的位置
rm(list=ls())
文件夹
setwd('') # direct R to where the files are stored
rm(list=ls())
files <- list.files()
for(file in files){
name <- paste(file)
name <- assign(name, read.csv(file))
}
data_sets <- grep('_', ls(), value = T)
allData <- data.frame()
for(i in data_sets){
dat <- get(i)
station_end <- data.frame(str_locate(i, '_'))$start - 1
year_end <- data.frame(str_locate(i, '_'))$end + 4
dat$station <- str_sub(i, 1, station_end)
dat$year <- str_sub(i, station_end + 2, year_end)
allData <- rbind(allData, dat)
}
allData