Creating a dataframe based on two other dataframes using dplyr in R


These are my dataframes:

df<-,, 25))


I'd like to make the finaldf finaldf sort the columns like this:


As my original dataframe is much bigger, I need a more robust code, which is beyond my capacity considering that I'm new to R.

Note that the idea is to simply take columns from the df dataframe and throw them into the dataframe. But these columns must fit in the order established by the dataframe.

And I would like to do this using the dplyr package. It's possible?


Well, my original code comes with the names of the stocks on the Bovespa:<-c("ABEV3.BBAS3", "", "ABEV3.BRAP4", "", 
"ABEV3.BRKM5", "", "ABEV3.CSAN3", "", 
"ABEV3.CSNA3", "", "ABEV3.CYRE3", "", 
"ABEV3.DTEX3", "", "ABEV3.ELPL4", "", 
"ABEV3.EVEN3", "", "ABEV3.FIBR3", "", 
"ABEV3.GGBR4", "", "ABEV3.GOAU4", "", 
"ABEV3.HYPE3", "", "ABEV3.JBSS3", "","SANB11.BBAS3","")

I would need to separate what comes before and after the period and not 1 in 1. Sometimes it comes 5 letters before the period, sometimes it comes 6 letters.


Here goes.
The trick is to group by the first few characters of names(finaldf) and then process the list of groups.

First we choose the names that interest us.

nms <- names(finaldf)
nms <- nms[sapply(nms, nchar) > 1]

Now they are grouped by the first 3 characters.

sp <- split(nms, substr(nms, 1, 3))
nms <- lapply(sp, function(s) c(substr(s[1], 1, 1), s))
nms <- unlist(nms)
result <- finaldf[nms]

The result result has the dimensions of the question.

#[1]  8 30

But beware, as there cannot be repeated names, there will be A , A.1 and A.2 . And the same thing for any others where there are repetitions, for example HI and HK .

# [1] "A"       "A.B"     "" "A.1"     "A.C"     ""
# [7] "A.2"     "A.F"     "" "B"       "B.C"     ""
#[13] "C"       "C.D"     "" "F"       "F.G"     ""
#[19] "H"       "H.I"     "" "H.1"     "H.K"     ""
#[25] "L"       "L.M"     "" "N"       "N.Q"     ""
Scroll to Top