gpt4 book ai didi

r - 如何将具有几行代码的字符数组转换为 data.frame?

转载 作者:行者123 更新时间:2023-12-01 08:52:10 24 4
gpt4 key购买 nike

我有以下数组
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")

产生的最短代码是什么:

  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.

还有什么更优雅的吗?

最佳答案

data.table 包中的

tstrsplitstringr 中的 str_split_fixed 是获取正确形状数据的非常有用的函数分割字符串向量时;前者提供了拆分字符串的transpose,允许您在不使用apply函数的情况下单独提取日期和时间,后者将字符串拆分为具有指定列的矩阵:

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"

关于r - 如何将具有几行代码的字符数组转换为 data.frame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38797026/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com