geo*_*007 5 regex split r dataframe
我试图在一个相当不整洁的数据帧中分隔一列.
section
View 500
V458
453
Run Code Online (Sandbox Code Playgroud)
我想从中创建一个新列.使用如下的首选输出.
section section numbers
View 500
V 458
453
Run Code Online (Sandbox Code Playgroud)
我一直在努力研究它,但我有时间用它.我可以在第一行的情况下将它们分开,因为我可以像这样使用正则表达式.
df_split <- separate(df, col = section, into = c("section", "section_number"), sep = " +[1-9]")
Run Code Online (Sandbox Code Playgroud)
但我似乎无法找到使用"或"类型语句的方法.如果有人有任何输入,那将是美好的.
使用简单gsub将是我的选择:
section <- c('View 500', 'V458', '453')
cbind(section = trimws(gsub('[0-9]', '', section)),
section_numbers = trimws(gsub('[a-zA-Z]', '', section)))
Run Code Online (Sandbox Code Playgroud)
我trimws用来删除任何不需要的空格.
输出:
section section_numbers
[1,] "View" "500"
[2,] "V" "458"
[3,] "" "453"
Run Code Online (Sandbox Code Playgroud)
你可以使用tidyr这个:
tidyr::extract(df,section, c("section", "section number"),
regex="([[:alpha:]]*)[[:space:]]*([[:digit:]]*)")
section section number
1 View 500
2 V 458
3 453
Run Code Online (Sandbox Code Playgroud)