Home > Software engineering >  How can I separate the data frame of one column into two columns in R?
How can I separate the data frame of one column into two columns in R?

Time:07-07

How can I separate the data frame of one column into two columns in R?

This the dput(head(taxonomy, n=30))

structure(list(X1..Neodiprion.virginianus = c("    species, hymenopterans", 
"2. Nepsalus jezoensis", "    species, insects", "3. Prochas sp. 2 YYH-2022a", 
"    species, wasps, ants & bees", "4. Prochas sp. 1 YYH-2022a", 
"    species, wasps, ants & bees", "5. Eccoptopterus sp. 1 CP-2022", 
"    species, beetles", "6. Andricus sp. 1 CYS-2022a", "    species, wasps, ants & bees", 
"7. Paralabellula curvicauda", "    species, earwigs", "8. Paralabellula", 
"    genus, earwigs", "9. Pristiphora sp.", "    species, hymenopterans", 
"10. Phyllotreta flexuosa", "    species, beetles", "11. Nematinae sp.", 
"    species, hymenopterans", "12. Euura sp.", "    species, hymenopterans", 
"13. Dolerus sp.", "    species, hymenopterans", "14. Ivieolus inflaticollis", 
"    species, beetles", "15. Germarostes sp.", "    species, beetles", 
"16. Germarostes globosus")), row.names = c(NA, 30L), class = "data.frame")

I need the folowing data frame: [![enter image description here][1]][1]

Many thanks! [1]: https://i.stack.imgur.com/ly1ho.png

CodePudding user response:

You can use the fact that row indices are recycled so c(T,F) will get every other row starting with the first row and c(F,T) will get every other row starting with the second row:

data.frame(x = df[c(F,T),], y = trimws(df[c(T,F),]))

Output

                                x                           y
1           2. Nepsalus jezoensis      species, hymenopterans
2      3. Prochas sp. 2 YYH-2022a            species, insects
3      4. Prochas sp. 1 YYH-2022a species, wasps, ants & bees
4  5. Eccoptopterus sp. 1 CP-2022 species, wasps, ants & bees
5     6. Andricus sp. 1 CYS-2022a            species, beetles
6     7. Paralabellula curvicauda species, wasps, ants & bees
7                8. Paralabellula            species, earwigs
8              9. Pristiphora sp.              genus, earwigs
9        10. Phyllotreta flexuosa      species, hymenopterans
10              11. Nematinae sp.            species, beetles
11                  12. Euura sp.      species, hymenopterans
12                13. Dolerus sp.      species, hymenopterans
13     14. Ivieolus inflaticollis      species, hymenopterans
14            15. Germarostes sp.            species, beetles
15       16. Germarostes globosus            species, beetles
  •  Tags:  
  • r
  • Related