在一列中包装文本观察

时间:2014-12-01 20:16:58

标签: r

我的数据框中有一列,此列包含以;分隔的文本数据;

 x1 =c ("Anal Exam Under ;", "Sigmoidoscopy;Colonoscopy; Esophagogastroduodenoscopy;" ,"Fistula                  
 Repair;Percutaneous Endo. G-Tube (PEG);" ,"Sigmoidoscopy;Anorectal Motility/Anorectal Manometry 
 (ARMS);","Sigmoidoscopy;Colonoscopy;", "Procedure; Auditory Brain Stem ;", "Colonoscopy; EGD 
 (Endoscopy Upper GI);", "Eye Exam; Lumbar Puncture; MRI Scan;
 EGD (Endoscopy Upper GI);", "EUS Upper GI (Endoscopic Ultrasound); Sigmoidoscopy;")

 x1
 [1] "Anal Exam Under ;"                                              
 [2] "Sigmoidoscopy;Colonoscopy; Esophagogastroduodenoscopy;"         
 [3] "Fistula Repair;Percutaneous Endo. G-Tube (PEG);"                
 [4] "Sigmoidoscopy;Anorectal Motility/Anorectal Manometry (ARMS);"   
 [5] "Sigmoidoscopy;Colonoscopy;"                                     
 [6] "Procedure; Auditory Brain Stem ;"                               
 [7] "Colonoscopy; EGD (Endoscopy Upper GI);"                         
 [8] "Eye Exam; Lumbar Puncture; MRI Scan;\nEGD (Endoscopy Upper GI);"
 [9] "EUS Upper GI (Endoscopic Ultrasound); Sigmoidoscopy;"  

如果遇到文本,我如何将文本换行到该单元格中的新行(不是新行),新行;

例如,第二次和第三次观察是

  [2] "Sigmoidoscopy;Colonoscopy; Esophagogastroduodenoscopy;"
  [3] "Fistula Repair;Percutaneous Endo. G-Tube (PEG);"

我希望它看起来像

  [2] "Sigmoidoscopy;Colonoscopy; 
       Esophagogastroduodenoscopy;"
  [3] "Fistula Repair;
       Percutaneous Endo. G-Tube (PEG);"

需要一些帮助。

1 个答案:

答案 0 :(得分:1)

使用gsub();的所有实例替换为前导和尾随空格。

试试这个:

z <- gsub(" *; *\n* *", "\n", x1)
cat(z)

结果

Anal Exam Under
 Sigmoidoscopy
Colonoscopy
Esophagogastroduodenoscopy
 Fistula                  
 Repair
Percutaneous Endo. G-Tube (PEG)
 Sigmoidoscopy
Anorectal Motility/Anorectal Manometry 
 (ARMS)
 Sigmoidoscopy
Colonoscopy
 Procedure
Auditory Brain Stem
 Colonoscopy
EGD 
 (Endoscopy Upper GI)
 Eye Exam
Lumbar Puncture
MRI Scan
EGD (Endoscopy Upper GI)
 EUS Upper GI (Endoscopic Ultrasound)
Sigmoidoscopy