Split data.frame into groups by column name

I am new to R. I have a data frame with column names of this type:

file_001   file_002   block_001   block_002   red_001   red_002 ....etc'  
  0.05       0.2        0.4         0.006       0.05       0.3
  0.01       0.87       0.56        0.4         0.12       0.06

I want to break them into groups by column name to get this result:

group_file
file_001   file_002
  0.05       0.2
  0.01       0.87

group_block
block_001   block_002
  0.4        0.006
  0.56       0.4

group_red
red_001    red_002
  0.05       0.3
  0.12       0.06

...etc'

My file is huge. I do not have a certain number of groups. It should be just by the name of the column.

+5
source share
2 answers

In the R database, you can use suband split.default, like this, to return a list of data.frames:

myDfList <- split.default(dat, sub("_\\d+", "", names(dat)))

it returns

myDfList
$block
  block_001 block_002
1      0.40     0.006
2      0.56     0.400

$file
  file_001 file_002
1     0.05     0.20
2     0.01     0.87

$red
  red_001 red_002
1    0.05    0.30
2    0.12    0.06

split.default data.frames . sub "_\d +", , , "block", "file" "red".

, lapply. . Gregor .

+7

, lmo, , , .

, Data Frame:

myDfList <- split.default(dat, sub(x = as.character(names(dat)), pattern = "\\_.*", ""))

, !

0

Source: https://habr.com/ru/post/1689255/


All Articles