如何按名称拆分数据框的列?

时间:2022-04-29 21:45:12

I have a dataframe df:

我有一个数据帧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:

我想将列拆分为1 b 2 c 33,如下所示:

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

How can this be done, please advise?

如何做到这一点,请指教?

1 个解决方案

#1


2  

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):

使用rep和strsplit的组合(对于名称):

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

#1


2  

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):

使用rep和strsplit的组合(对于名称):

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