如何将带有几行代码的字符数组转换为data.frame? [英] How can I transform an array of characters with a few lines of code to a data.frame?

查看:59
本文介绍了如何将带有几行代码的字符数组转换为data.frame?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数组
my_list <- c("Jan-01--Dec-31|00:00--24:00", "Jan-01--Jun-30|12:00--18:00", "Jul-06--Dec-31|09:00--19:00")

I have the following array
my_list <- c("Jan-01--Dec-31|00:00--24:00", "Jan-01--Jun-30|12:00--18:00", "Jul-06--Dec-31|09:00--19:00")

最短的代码是什么导致的结果:

What is the shortest code which results in:

  x1     x2     x3
1 Jan-01 Jan-01 Jul-06
2 Dec-31 Jun-30 Dec-31

  x2    x2    x3
1 00:00 12:00 09:00
2 24:00 18:00 19:00

此刻,我有(不太好)的代码

df <- as.data.frame(strsplit(my_list, split = "|", fixed = T),
                    stringsAsFactors = F)
date_list <- strsplit(as.character(df[1, ]), split = "--", fixed = T)
date_df <- as.data.frame(date_list, col.names = c(1:length(date_list)),
                         stringsAsFactors = F)
time_list <- strsplit(as.character(df[2, ]), split = "--", fixed = T)
time_df <- as.data.frame(time_list, col.names = c(1:length(date_list)),
                         stringsAsFactors = F)

我到目前为止最好的是

date_list <- sapply(strsplit(schedule$schedule, split = "|", fixed = T), "[", 1)
date_df <- t(data.frame(x1=sapply(strsplit(df1, split = "--", fixed = T), "[", 1),
                   x2=sapply(strsplit(df1, split = "--", fixed = T), "[", 2),
                   stringsAsFactors = F))
# and similarly for time_list and time_df.

还有更优雅的东西吗?

包中的

tstrsplitstringr中的str_split_fixed是非常有用的函数,用于在分割字符串矢量时获取正确的整形数据.前者提供了拆分字符串的transpose,它使您无需使用apply函数即可分别提取日期和时间,而后者提供了将字符串拆分为具有指定列的矩阵:

tstrsplit from data.table package and str_split_fixed from stringr are pretty useful functions to get correct shaped data when splitting vectors of strings; The former provides transpose of the splitted string which allows you to extract the date and time separately without using apply function and the latter split strings into matrix with specified columns:

library(data.table); library(stringr)
lapply(tstrsplit(my_list, "\\|"), function(s) t(str_split_fixed(s, "--", 2)))

#[[1]]
#     [,1]     [,2]     [,3]    
#[1,] "Jan-01" "Jan-01" "Jul-06"
#[2,] "Dec-31" "Jun-30" "Dec-31"

#[[2]]
#     [,1]    [,2]    [,3]   
#[1,] "00:00" "12:00" "09:00"
#[2,] "24:00" "18:00" "19:00"

这篇关于如何将带有几行代码的字符数组转换为data.frame?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆