Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
948 views
in Technique[技术] by (71.8m points)

dataframe - Split a column into 2 in R

 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)

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

I tried

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

but stuck at converting location3 from list to dataframe

I tried

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

but I get an error

Error in UseMethod("separate_") : no applicable method for 'separate_' applied to an object of class "character"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...