2017-03-04 38 views
0

我在全球環境中有許多數據框,我們稱它們爲a,bc轉換多個數據幀的相同列

每個數據幀都有一個名爲start_time的列,需要將其轉換爲posix類,但我正在尋找方法來完成此操作,而無需爲每個數據幀編寫相同的代碼。該代碼是:

a$start_time <- strptime(a$start_time, format = '%Y-%m-%d %H:%M:%S') 

這隻會轉換start_timea

使用數據幀的名字,​​一個人如何可以設計一個地遍歷每個dataframes和轉換start_time POSIX的?

這種嘗試用lapply只適用於第一個數據幀...

ll <- list(a, b, c) 
lapply(ll,function(df){ 
    df$start_time <- strptime(df$start_time, format = '%Y-%m-%d %H:%M:%S')   

}) 

回答

1

數據:df1df2df3

df1 <- data.frame(start_time = seq(Sys.time(), Sys.time() + 100, 10))  
df2 <- data.frame(start_time = seq(Sys.time(), Sys.time() + 100, 10))  
df3 <- data.frame(start_time = seq(Sys.time(), Sys.time() + 100, 10)) 

# create a vector with names of the data frames 
data_vec <- c('df1', 'df2', 'df3') 

# loop through the data_vec and modify the start_time column 
a1 <- lapply(data_vec, function(x) { 
    x <- get(x) 
    x <- within(x, start_time <- strptime(start_time, format = '%Y-%m-%d %H:%M:%S')) 
    return(x) 
    }) 

# assign names to the modified data in a1 
names(a1) <- data_vec 

# list objects in global environment 
ls() 
# [1] "a1"  "data_vec" "df1"  "df2"  "df3" 

# remove df1, df2, df3 from global environment 
rm(list = c('df1', 'df2', 'df3')) 

# confirm the removal of data 
ls() 
# [1] "a1"  "data_vec" 

# assign the named list in a1 as data in global environment 
list2env(a1, envir = .GlobalEnv) 

# list objects in global environment and confirm that the data appeared again 
ls() 
# [1] "a1"  "data_vec" "df1"  "df2"  "df3"  

# output 
head(df1) 
#   start_time 
# 1 2017-03-03 22:49:54 
# 2 2017-03-03 22:50:04 
# 3 2017-03-03 22:50:14 
# 4 2017-03-03 22:50:24 
# 5 2017-03-03 22:50:34 
# 6 2017-03-03 22:50:44 

head(df2) 
#   start_time 
# 1 2017-03-03 22:49:54 
# 2 2017-03-03 22:50:04 
# 3 2017-03-03 22:50:14 
# 4 2017-03-03 22:50:24 
# 5 2017-03-03 22:50:34 
# 6 2017-03-03 22:50:44 
+0

有趣的工作流程,即工作 –

1

在OP的代碼,並沒有返回的數據集。因此,它基本上是

lapply(ll,function(df){ 
    df$start_time <- strptime(df$start_time, format = '%Y-%m-%d %H:%M:%S')   
    df 
}) 

但是,沒有返回對象和匿名函數調用,transform是一個選項。另外,strptime也返回POSIXlt類。如果我們只需要POSIXct,使用as.POSIXct

lapply(ll, transform, start_time = as.POSIXct(start_time, format = '%Y-%m-%d %H:%M:%S')) 

或者使其更爲緊湊

library(lubridate) 
lapply(ll, transform, start_time = ymd_hms(start_time))