0

我有两个向量,向量“t”是时间,向量“d”是日期。 我
想为 d 中的所有日期在 t 中提取所有时间的数据
使用如下:

    t <- c("11:25:30", "12:00:00", "15:31:25", "19:15:48", "23:51:06")
    d <- c("2013-01-17", "2013-01-24", "2013-02-09", "2013-02-11")  
    c1 <- sapply(d, function(i) paste(d[i],t))

我希望在使用带有字符串“”“2013-01-17 11:25:30”、“2013-01-17 12:00:00”、2013-01-17 的 sapply 时使用 lapply 或向量时看到一个列表15:31:25" ... 一直到最后,将每个日期与 t 中的所有时间结合起来。

4

3 回答 3

5

这是最快的方法,并且具有输入最少的额外好处:

c(outer(d, t, paste))

##  [1] "2013-01-17 11:25:30" "2013-01-24 11:25:30" "2013-02-09 11:25:30"
##  [4] "2013-02-11 11:25:30" "2013-01-17 12:00:00" "2013-01-24 12:00:00"
##  [7] "2013-02-09 12:00:00" "2013-02-11 12:00:00" "2013-01-17 15:31:25"
## [10] "2013-01-24 15:31:25" "2013-02-09 15:31:25" "2013-02-11 15:31:25"
## [13] "2013-01-17 19:15:48" "2013-01-24 19:15:48" "2013-02-09 19:15:48"
## [16] "2013-02-11 19:15:48" "2013-01-17 23:51:06" "2013-01-24 23:51:06"
## [19] "2013-02-09 23:51:06" "2013-02-11 23:51:06"
于 2013-04-26T18:29:31.163 回答
2

你可以expand.grid()结合apply(). expand.grid() 将制作 和 的所有可能组合的数据dt。withapply()函数paste()应用于此数据帧的每一行。collapse=" "确保字符串放在一起并在它们之间放置空间。

apply(expand.grid(d,t),1,paste,collapse=" ")

 [1] "2013-01-17 11:25:30" "2013-01-24 11:25:30" "2013-02-09 11:25:30"
 [4] "2013-02-11 11:25:30" "2013-01-17 12:00:00" "2013-01-24 12:00:00"
 [7] "2013-02-09 12:00:00" "2013-02-11 12:00:00" "2013-01-17 15:31:25"
[10] "2013-01-24 15:31:25" "2013-02-09 15:31:25" "2013-02-11 15:31:25"
[13] "2013-01-17 19:15:48" "2013-01-24 19:15:48" "2013-02-09 19:15:48"
[16] "2013-02-11 19:15:48" "2013-01-17 23:51:06" "2013-01-24 23:51:06"
[19] "2013-02-09 23:51:06" "2013-02-11 23:51:06"
于 2013-04-26T18:03:48.153 回答
2

你可以像这样使用expand.gridpaste

t <- c("11:25:30", "12:00:00", "15:31:25", "19:15:48", "23:51:06")
d <- c("2013-01-17", "2013-01-24", "2013-02-09", "2013-02-11") 
do.call("paste", expand.grid(d,t))
 [1] "2013-01-17 11:25:30" "2013-01-24 11:25:30" "2013-02-09 11:25:30"
 [4] "2013-02-11 11:25:30" "2013-01-17 12:00:00" "2013-01-24 12:00:00"
 [7] "2013-02-09 12:00:00" "2013-02-11 12:00:00" "2013-01-17 15:31:25"
[10] "2013-01-24 15:31:25" "2013-02-09 15:31:25" "2013-02-11 15:31:25"
[13] "2013-01-17 19:15:48" "2013-01-24 19:15:48" "2013-02-09 19:15:48"
[16] "2013-02-11 19:15:48" "2013-01-17 23:51:06" "2013-01-24 23:51:06"
[19] "2013-02-09 23:51:06" "2013-02-11 23:51:06"

我还没有找到一种方法来调整使用此语法的sep参数paste,但它提供了您需要的输出。

于 2013-04-26T18:08:35.600 回答