这个问题在这里已有答案:
我有一个包含文本和数字的数据框,我想在单独的列中拆分,排序和组合文本和数字。请找到示例数据集。
Text
7 LIFTING & SHORING
-00 General
-10 Jacking
-20 Shoring
8 LEVELING & WEIGHING
-00 General
-10 Weighing and Balancing
-20 Leveling
我需要得到以下结果:
dig Desc.
700 LIFTING & SHORING General
710 LIFTING & SHORING Jacking
720 LIFTING & SHORING Shoring
800 LEVELING & WEIGHING General
810 LEVELING & WEIGHING Weighing and Balancing
820 LEVELING & WEIGHING Leveling
我尝试在R中使用for循环,但我是r中的新手并且找不到任何解决方案。
我感谢您的帮助。
使用tidyverse
:
library(tidyverse)
df %>%
separate(Text,c("text1","text2"),"^-") %>%
mutate(text1 = ifelse(text1 == "", NA, text1)) %>%
fill(text1) %>%
filter(!is.na(text2)) %>%
separate(text1,c("dig1","Desc1"),convert = TRUE,extra="merge") %>%
separate(text2,c("dig2","Desc2"),convert = TRUE,extra="merge") %>%
transmute(dig = dig1*100+dig2,
Desc. = paste(Desc1,Desc2))
# dig Desc.
# 1 700 LIFTING & SHORING General
# 2 710 LIFTING & SHORING Jacking
# 3 720 LIFTING & SHORING Shoring
# 4 800 LEVELING & WEIGHING General
# 5 810 LEVELING & WEIGHING Weighing and Balancing
# 6 820 LEVELING & WEIGHING Leveling
数据
df <- read.table(text="Text
'7 LIFTING & SHORING'
'-00 General'
'-10 Jacking'
'-20 Shoring'
'8 LEVELING & WEIGHING'
'-00 General'
'-10 Weighing and Balancing'
'-20 Leveling'",strin=F,h=T)