创建多个数据框

时间:2021-01-17 15:42:14

标签: r dplyr

我有一个如下所示的数据框(df):

enter image description here

目标:我想创建52个DATAFRAMES,不知道怎么用dplyr

enter image description here

2 个答案:

答案 0 :(得分:0)

尝试下一个代码:

library(dplyr)
library(tidyr)
#Code
new <- df %>% pivot_longer(-1) %>%
  group_by(name) %>%
  filter(!is.na(value))
#List
List <- split(new,new$name)
#Set to envir
list2env(List,envir = .GlobalEnv)

使用的一些数据:

#Data
df <- structure(list(id_unico = c("112172-1", "112195-1", "112257-1", 
"112268-1", "112383-1", "112452-1", "112715-1", "112716-1", "112761-1", 
"112989-1"), P101COD = c(NA, NA, NA, NA, NA, 411010106L, NA, 
NA, 411010106L, NA), P102COD = c(421010102L, 421010102L, 421010102L, 
421010102L, 421010102L, NA, 421010108L, 421010108L, NA, 421010102L
), P103COD = c(441010109L, 441010109L, 441010109L, 441010109L, 
441010109L, 441010109L, 441010109L, 441010109L, 441010109L, 441010101L
), P110_52_COD = c(NA, 831020103L, 831020103L, NA, 831020103L, 
NA, NA, NA, NA, NA)), class = "data.frame", row.names = c(NA, 
-10L))

答案 1 :(得分:0)

假设您的数据框位于变量 df 中,请尝试以下代码:

library(dplyr)

columns_name = names(df)     #names of column in your dataframe    
df_list =list()  #empty list to store output dataframes

#loop through columns of the original dataframe,
#selecting the first and i_th column and storing the resulting dataframe in a list

for (i in 1:(length(columns_name) -1)){
  df_list[[i]] = df %>% select(columns_name[1],columns_name[i+1]) %>% filter_all(all_vars(!is.na(.)))
}

#access smaller dataframes using the following code
df_list[[1]]   
df_list[[2]]