Dr. Richard Tennen
Dr. Richard Tennen

Reputation: 267

How to split the columns of a dataframe by their name?

I have a dataframe df:

a.1 b.2  c.33 ...
1   kuku 3
44  bubu 441
55  wewe 4441

I want to split the column to be a 1 b 2 c 33 like this:

a   1  b    2
1   1  kuku kuku 
44  44 bubu bubu 
55  55 wewe wewe .....

How can this be done, please advise?

Upvotes: 0

Views: 45

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193497

Starting with:

mydf <- structure(list(a.1 = c(1L, 44L, 55L), b.2 = c("kuku", "bubu", 
    "wewe"), c.33 = c(3L, 441L, 4441L)), .Names = c("a.1", "b.2", 
    "c.33"), row.names = c(NA, 3L), class = "data.frame")

Use a combination of rep and strsplit (for the names):

setNames(data.frame(rep(mydf, each = 2)), 
         unlist(strsplit(names(mydf), ".", TRUE)))
##    a  1    b    2    c   33
## 1  1  1 kuku kuku    3    3
## 2 44 44 bubu bubu  441  441
## 3 55 55 wewe wewe 4441 4441

Upvotes: 2

Related Questions