简体   繁体   English

按每个字符将字符串分隔成列

[英]Separate string to columns by each character

in my dataframe I have a column with long string like this 在我的数据框中,我有一列这样的长字符串

df$string 
AVDSFBKLDF

What I need is to separate each character and create new column for it. 我需要的是分隔每个字符并为其创建新列。 Name of the columns is q1, q2 and so on. 列的名称是q1,q2,依此类推。 For similar cases like spliting string by symbol and put it into the new columns I used this code 对于类似的情况,例如按符号分割字符串并将其放入新列中,我使用了此代码

df %>% separate(string, into = paste0('q', 1:10), sep = "")

It worked fine but now when I want to split string by each characters I'm getting some blank warning my console and my code do not works. 它工作正常,但是现在当我想按每个字符分割字符串时,控制台出现空白警告,我的代码不起作用。

The data.table package provides the function tstrsplit that you might consider. data.table包提供您可能考虑的功能tstrsplit

a<- c("AVDSFBKLDF", "GH", "ABCD")

library(data.table)
DT <- data.table(a)
DT_wide <- DT[, tstrsplit(a, "")]

# change column names
setnames(DT_wide, paste0("q", seq_len(ncol(DT_wide))))
DT_wide
#   q1 q2   q3   q4   q5   q6   q7   q8   q9  q10
#1:  A  V    D    S    F    B    K    L    D    F
#2:  G  H <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>
#3:  A  B    C    D <NA> <NA> <NA> <NA> <NA> <NA>

If you want to continue to work with a dataframe, type setDF(DT_wide) at the end. 如果要继续使用数据setDF(DT_wide) ,请在最后键入setDF(DT_wide)

Use the below code. 使用下面的代码。 i have used stringr package str_split_fixed function to create new columns. 我已经使用了Stringr包的str_split_fixed函数来创建新列。

a<- c("AVDSFBKLDF")

library(stringr)
d<- data.frame(str_split_fixed(a, "", max(nchar(a))))

I hope this helps 我希望这有帮助

You could try : 您可以尝试:

df<- data.frame(string=c("ABCDEF","GH"))
df %>% mutate(v=str_split(string,"(?=.)")) %>% unnest %>%
  filter(v!="") %>% 
  group_by(string) %>% mutate(k=paste0("q",row_number())) %>% ungroup %>%
  spread(k,v) 
## A tibble: 2 x 7
#  string q1    q2    q3    q4    q5    q6   
#  <fct>  <chr> <chr> <chr> <chr> <chr> <chr>
#1 ABCDEF A     B     C     D     E     F    
#2 GH     G     H     <NA>  <NA>  <NA>  <NA>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM