Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

r - Match column names with another dataframe and split into separate dataframes

I've got a dataframe (df) which looks like this:

tex21.222   chic56.345  wa34.907
0.5         0.6         1.12
0.8         1.2         0.9

I want to partition this dataframe into separate dataframes, based on another dataframe called keys, which looks like this:

site_name   sample_name
tex_1       tex21.222
tex_1       tex23.234
chic_1      chic56.345 
wa_1        wa34.907
wa_2        wa24.277

For every column of df, I want to (1) match the column name with sample_name in keys to get site_name, (2) move all columns that have the same site_name from df into separate dataframes.

So, in the end, I want to have separate dataframes with all columns that fall within tex_1, all columns that fall within chic_1 etc.

How can I do this?

question from:https://stackoverflow.com/questions/65847609/match-column-names-with-another-dataframe-and-split-into-separate-dataframes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try next code:

library(dplyr)
library(tidyr)
#Code
data <- df %>% pivot_longer(everything()) %>%
  left_join(keys,by = c('name'='sample_name'))
#Split
List <- split(data,data$site_name)
List <- lapply(List,function(x) {x$site_name<-NULL;x})
list2env(List,envir = .GlobalEnv)

Outputs:

List
$chic_1
# A tibble: 2 x 2
  name       value
  <chr>      <dbl>
1 chic56.345   0.6
2 chic56.345   1.2

$tex_1
# A tibble: 2 x 2
  name      value
  <chr>     <dbl>
1 tex21.222   0.5
2 tex21.222   0.8

$wa_1
# A tibble: 2 x 2
  name     value
  <chr>    <dbl>
1 wa34.907  1.12
2 wa34.907  0.9 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...