0

I have a dataframe(df) that looks like below:

enter image description here

Objective: I want to create 52 DATAFRAMES, I don't know how to use it with dplyr

enter image description here

2 Answers 2

1

Assuming your dataframe is in variable df, try the following code:

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]] 
Sign up to request clarification or add additional context in comments.

Comments

0

Try next code:

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)

Some data used:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.