本文介绍了在R中将一列拆分为2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 I have this dataframe

      CC.Number       Date Time Accident.Type              Location.1
    1 12T008826 07/01/2012 1630            PD  (39.26699, -76.560642)
    2 12L005385 07/02/2012 1229            PD (39.000549, -76.399312)
    3 12L005388 07/02/2012 1229            PD  (39.00058, -76.399267)
    4 12T008851 07/02/2012  445            PI   (39.26367, -76.56648)
    5 12T008858 07/02/2012  802            PD (39.240862, -76.599017)
    6 12T008860 07/02/2012  832            PD   (39.27022, -76.63926)

我想将Location.1列拆分为"alt"和"lng"列

I want to split the column Location.1 to "alt" and "lng" columns to be like

  CC.Number       Date Time Accident.Type      alt       lng
1 12T008826 07/01/2012 1630            PD  39.26699    -76.560642
2 12L005385 07/02/2012 1229            PD  39.000549   -76.399312
3 12L005388 07/02/2012 1229            PD  39.00058    -76.399267

我尝试了

location <- md$Location.1
location1 <- substring(location, 2)
location2 <- substr(location1, 1, nchar(location1)-1 )
location3 <-  strsplit(location2, ",")

但停留在将location3从列表转换为数据框的过程中

but stuck at converting location3 from list to dataframe

我尝试了

ocdf<-data.frame(location2)
colnames(locdf)[1] = c("x")
df <- separate(location, col=x,into = c("lat","log"), sep = ",")

但是我得到一个错误

推荐答案

tidyr 分开也可以

separate from tidyr also works

library(tidyr)
# Sub out the parentheses
df$Location.1 <- gsub("[()]", "", df$Location.1)

separate(df, col = Location.1, into = c("lat","long"), sep = ",")
#  CC.Number       Date Time Accident.Type       lat        long
#1 12T008826 07/01/2012 1630            PD  39.26699  -76.560642
#2 12L005385 07/02/2012 1229            PD 39.000549  -76.399312
#3 12L005388 07/02/2012 1229            PD  39.00058  -76.399267
#4 12T008851 07/02/2012  445            PI  39.26367   -76.56648
#5 12T008858 07/02/2012  802            PD 39.240862  -76.599017
#6 12T008860 07/02/2012  832            PD  39.27022   -76.63926

这篇关于在R中将一列拆分为2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-31 12:57