从r

时间:2018-11-14 23:09:48

标签: r date dataframe time

我有一组数据,其中日期,时间和速度已合并到一个单独的列中,desciptio

  coordinates     Name                                descriptio
1 (-123.3397, 50.07757) HAR07(0) Timestamp: 08/16/2018 03:44:00 Speed: 0.8
2 (-123.3396, 50.07787) HAR07(1) Timestamp: 08/16/2018 07:46:00 Speed: 0.1
3 (-123.3397, 50.07755) HAR07(2) Timestamp: 08/16/2018 11:50:00 Speed: 0.0
4 (-123.3616, 50.11495) HAR07(3) Timestamp: 08/17/2018 04:01:00 Speed: 0.1
5 (-123.3289, 50.10053) HAR07(4) Timestamp: 08/18/2018 04:22:00 Speed: 0.4
6 (-123.3514, 50.10265) HAR07(5) Timestamp: 08/19/2018 04:44:00 Speed: 0.1

我正在寻找一种提取这些值并将它们作为单独的列datetimespeed添加到数据框中的方法。我已经看到了一些提取日期甚至时间的方法,但是我对速度确实感到迷惑。我确实发现了this这个问题,看起来很相似,但是我对正则表达式不太熟悉,无法适应我的需求。有什么建议吗?

谢谢!

编辑:这些数据在shapefile中,而不是数据框中。我想我可以将它们读入数据框中,进行编辑,然后将其重新保存为shapefile,但我更愿意在可能的情况下始终将其保留为空间数据。

2 个答案:

答案 0 :(得分:0)

去那里:

df <- read.table(header=TRUE,stringsAsFactors=FALSE,text="  coordinates     Name                                descriptio
1 '(-123.3397, 50.07757)' HAR07(0) 'Timestamp: 08/16/2018 03:44:00 Speed: 0.8'
2 '(-123.3396, 50.07787)' HAR07(1) 'Timestamp: 08/16/2018 07:46:00 Speed: 0.1'
3 '(-123.3397, 50.07755)' HAR07(2) 'Timestamp: 08/16/2018 11:50:00 Speed: 0.0'
4 '(-123.3616, 50.11495)' HAR07(3) 'Timestamp: 08/17/2018 04:01:00 Speed: 0.1'
5 '(-123.3289, 50.10053)' HAR07(4) 'Timestamp: 08/18/2018 04:22:00 Speed: 0.4'
6 '(-123.3514, 50.10265)' HAR07(5) 'Timestamp: 08/19/2018 04:44:00 Speed: 0.1'")

transform(df,
  date = as.Date(substr(descriptio,12,21),"%M/%d/%Y"),
  time = substr(descriptio,23,30),
  speed = as.numeric(substr(descriptio,39,41)))
#             coordinates     Name                                descriptio       date     time speed
# 1 (-123.3397, 50.07757) HAR07(0) Timestamp: 08/16/2018 03:44:00 Speed: 0.8 2018-11-16 03:44:00   0.8
# 2 (-123.3396, 50.07787) HAR07(1) Timestamp: 08/16/2018 07:46:00 Speed: 0.1 2018-11-16 07:46:00   0.1
# 3 (-123.3397, 50.07755) HAR07(2) Timestamp: 08/16/2018 11:50:00 Speed: 0.0 2018-11-16 11:50:00   0.0
# 4 (-123.3616, 50.11495) HAR07(3) Timestamp: 08/17/2018 04:01:00 Speed: 0.1 2018-11-17 04:01:00   0.1
# 5 (-123.3289, 50.10053) HAR07(4) Timestamp: 08/18/2018 04:22:00 Speed: 0.4 2018-11-18 04:22:00   0.4
# 6 (-123.3514, 50.10265) HAR07(5) Timestamp: 08/19/2018 04:44:00 Speed: 0.1 2018-11-19 04:44:00   0.1

R中没有时间的本机类型/类,因此我将其保留为字符。

答案 1 :(得分:0)

解决方案非常简单,如果比我想要的要冗长一些:

# Split column into 5 parts at each space
split <- str_split_fixed(raw.shp.data$descriptio, ' ', 5)

# Add the relevant columns back to the original data frame
raw.shp.data$time <- paste(split[,2], split[,3])
raw.shp.data$speed <- split[,5]

# Delete no-longer-needed descriptio column
raw.shp.data$descriptio <- NULL

这将使空间格式保持完整。