简体   繁体   中英

R: How do I convert a dataframe of strings into POSIXt objects?

I have a dataframe of strings representing times, such as:

times <- structure(list(exp1 = c("17:19:04 \r", "17:28:53 \r", "17:38:44 \r"), 
                        exp2 = c("17:22:04 \r", "17:31:53 \r", "17:41:45 \r")), 
                        row.names = c(NA, 3L), class = "data.frame")

If I run strptime() on a single element of my dataframe times , it converts it into a nice POSIXt object:

strptime(times[1,1], '%H:%M:%S')

[1] "2020-02-19 17:19:04 GMT"

Great, so now I'd like to convert my whole dataframe times into this format.

I cannot seem to find the solution to do this smoothly.

A few of the things I have tried so far:

strptime(times, '%H:%M:%S') # generates NA
strftime(times, '%H:%M:%S') # Error: do not know how to convert 'x' to class “POSIXlt”
apply(times, 2, function(x) strftime(x, '%H:%M:%S')) # Error: character string is not in a standard unambiguous format

The closest I got to what I want is:

apply(times, 2, function(x) strptime(x, '%H:%M:%S'))

It generates a messy list. I can probably find a way to use it, but there must be a more staightforward way?

You could use lapply .

times[] <- lapply(times, strptime, '%H:%M:%S')
#                  exp1                exp2
# 1 2020-02-19 17:19:04 2020-02-19 17:22:04
# 2 2020-02-19 17:28:53 2020-02-19 17:31:53
# 3 2020-02-19 17:38:44 2020-02-19 17:41:45

Note: apply also works.

times[] <- apply(times, 2, function(x) strptime(x, '%H:%M:%S'))

The trick is to replace the columns (in contrast to overwriting the data frame with a list) with [] <- , which can be seen as abbreviated for times[1:2] <- lapply(times[1:2], ·) in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM