简体   繁体   English

如何将两列合并为一列?

[英]How do I combine two columns into one?

I am stuck combining two columns of a data frame into one. 我坚持将数据帧的两列合并为一列。 Below is the code to reproduce the problem 下面是重现该问题的代码

df <- data.frame(date = c("2/13/1962 0:00:00", "4/13/1972 0:00:00", "3/13/1982 0:00:00", "12/13/1992 0:00:00"), 
                 time = c("0900", "1000", "1101", "1603"))

#This works
df$tmp <- as.Date(df$date, format="%m/%d/%Y")
df  

                date     time        tmp  
    1  2/13/1962 0:00:00 0900 1962-02-13  
    2  4/13/1972 0:00:00 1000 1972-04-13  
    3  3/13/1982 0:00:00 1101 1982-03-13  
    4 12/13/1992 0:00:00 1603 1992-12-13    


# this doesn't
df$tmp <- strptime(strsplit(as.character(df$date), " ")[[1]][1], format="%m/%d/%Y")
df

    1  2/13/1962 0:00:00 0900 1962-02-13
    2  4/13/1972 0:00:00 1000 1962-02-13
    3  3/13/1982 0:00:00 1101 1962-02-13
    4 12/13/1992 0:00:00 1603 1962-02-13    

I would like to end up with a column that combines the date part of the date and the time column but was unable to get to this result. 我想以一列结束,该列结合了日期和时间列的日期部分,但无法获得此结果。

While experimenting I noticed that the as.Date function does convert the date . 在进行实验时,我注意到as.Date函数确实转换了date。 On the other hand, with the strsplit function all rows end up with the first date. 另一方面,使用strsplit函数,所有行都以第一个日期结尾。

I would greatly appreciate any help towards a solution, ending up with 4 rows have a "Date" object: 我非常感谢提供解决方案的任何帮助,最后有4行有一个“ Date”对象:

    1 1962-02-13 09:00
    2 1972-04-13 10:00
    3 1982-03-13 11:01
    4 1992-12-13 16:03

You may paste the date and time variable, and then use as.POSIXct with appropriate format : 您可以paste日期和时间变量,然后以适当的format使用as.POSIXct

as.POSIXct(x = paste(as.Date(df$date, format = "%m/%d/%Y"), df$time),
           format = "%Y-%m-%d %H%M")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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