【问题标题】:Change Column Type within a For Loop in R for many similar data frames在 R 中的 For 循环中更改许多相似数据帧的列类型
【发布时间】:2020-09-19 11:56:25
【问题描述】:

在读取文件夹中具有相同结构的 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



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

【问题讨论】:

    标签: r dataframe


    【解决方案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)
    

    【讨论】:

    • 谢谢Ronak,这就是我想要达到的目标!。你是对的,将结果存储在列表中应该更容易。然而,我想要实现的是使用 plotly 为列表中的每个数据框创建一个绘图,但我不确定如何实现这一点,因为我对 plotly 很陌生,并且认为分别拥有每个数据框会帮助我暂时。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 2022-12-03
    • 2019-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多