问题
I have to import a table that look like as the following dataframe:
> df = data.frame(x = c("a", "a.b","a.b.c","a.b.d", "a.d"))
> df
x
1 <NA>
2 a
3 a.b
4 a.b.c
5 a.b.d
6 a.d
I'd like to separate the first column in one or more columns based one how many separator I'll find.
The output should lool like this
> df_separated
col1 col2 col3
1 a <NA> <NA>
2 a b <NA>
3 a b c
4 a b d
5 a d <NA>
I tried to use the separate function in tidyr but I need to specify a priori how many outoput columns I need.
Thank you very much for your help
回答1:
You can first count the number of columns it can take and then use separate
.
nmax <- max(stringr::str_count(df$x, "\\.")) + 1
tidyr::separate(df, x, paste0("col", seq_len(nmax)), sep = "\\.", fill = "right")
# col1 col2 col3
#1 a <NA> <NA>
#2 a b <NA>
#3 a b c
#4 a b d
#5 a d <NA>
来源:https://stackoverflow.com/questions/56356632/separate-a-column-of-a-dataframe-in-undefined-number-of-columns-with-r-tidyverse