1

在读取文件夹中具有相同结构的 csv 文件后,我试图将列类型从“chr”更改为“日期”

该代码可以很好地读取 csv 并将每个文件中的数据分配给单个变量,但是,当尝试将“日期”列更改为日期类型时,它会显示错误。

# Code to Read CSV files within a folder and change column type to date type

mydir <- "~/Desktop//Data/Downloads"
myfiles = list.files(path=mydir, pattern="*.csv", full.names=TRUE)

for (i in 1:length(myfiles)) {
    nam <- paste("price",i, sep = ".")
    assign(nam, read.csv(file = myfiles[i] , stringsAsFactors = FALSE)) # Code until here works fine
    price.i$date <- as.Date(price.i$date) # this part of the code generates the error
}

# Error
Error in as.Date(price.i$date) : object 'price.i' not found

# Example of Data read from each CSV file 
   str(price.1)
   'data.frame':    2195 obs. of  3 variables:
   symbol : chr "CAR" "CAR" "CAR"
   date : chr "2020-01-02" "2020-01-03" "2020-01-06"
   adjusted : num 16.5 16.6 16.7

# Expected Result
str(price.1)
   'data.frame':    2195 obs. of  3 variables:
   symbol : chr "CAR" "CAR" "CAR"
   date    : Date, format: "2020-01-02" "2020-01-03" "2020-01-06"
   adjusted : num 16.5 16.6 16.7



是否可以在循环中“子集”变量以更改列类型?

4

1 回答 1

1

您可以使用lapply循环读取文件并更改列类型。

result <- lapply(myfiles, function(x) {
  df <- read.csv(file = x, stringsAsFactors = FALSE)
  df$date <- as.Date(df$date) 
  df
})

您真的需要将数据作为全局环境中的单独对象吗?您可以将它们保存在 中的列表中result,以这种方式管理数据更容易。但是,如果您仍然需要单独使用它们,您可以使用list2env

names(result) <- paste0('price', seq_along(result))
list2env(result, .GlobalEnv)
于 2020-09-19T12:03:47.857 回答