Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - Split character string multiple times every two characters

I have a character column in my dataframe that looks like

df<-
  data.frame(a=c("AaBbCC","AABBCC","AAbbCC"))#df
       a
1 AaBbCC
2 AABBCC
3 AAbbCC

I would like to split this column every two characters. So in this case I would like to obtain three columns named VA,VB,VC. I tried

library(tidyr)
library(dplyr)
df<-
  data.frame(a=c("AaBbCC","AABBCC","AAbbCC"))%>%
  separate(a,c(paste("V",LETTERS[1:3],sep="")),sep=c(2,2))
 VA VB   VC
1 Aa    BbCC
2 AA    BBCC
3 AA    bbCC

but this is not the desired result. I like to have the result that is now in VC split into VB (all letter B) and VC (all letter C)How do I get R to split every two characters. The length of the string in the column is always the same for every row (6 in this example). I will have strings that are of length >10.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You were actually quite close. You need to specify the separator-positions as sep = c(2,4) instead of sep = c(2,2):

df <- separate(df, a, c(paste0("V",LETTERS[1:3])), sep = c(2,4))

you get:

> df
  VA VB VC
1 Aa Bb CC
2 AA BB CC
3 AA bb CC

In base R you could do (borrowing from @rawr's comment):

l <- ave(as.character(df$a), FUN = function(x) strsplit(x, '(?<=..)', perl = TRUE))
df <- data.frame(do.call('rbind', l))

which gives:

> df
  X1 X2 X3
1 Aa Bb CC
2 AA BB CC
3 AA bb CC

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...