Help with extracting all variables while removing NAs in each of these variables


I need to make individual datasets containing date and one variable from the entire dataset. Each variable has some NAs and we need to remove these NAs as well while retaining non-NA values. I am doing it variable by variable as of now. But if the number of variables become more, then this method is not efficient. Is there a way to do the same with all variables at the same time. Below is a small example to get the idea of what I am looking for.

x <- data.frame(
                                      date = c("2020-05-01",
                                       A = c(5081800.82485142,
                                    B = c(146.229784586414,
                                       C = c(48.211004603533,
                                       D = c(623692.818482367,

# Currently creating A, B, C, and D one by one.
A <- x%>%
  select(date, A)%>%

B <- x%>%
  select(date, B)%>%

D <- x%>%
  select(date, D)%>%

I would like to be able to achieve individual data sets A, B, C and D at once while also removing NAs from each of them.

Thanks for your help!

This does what you want

x %>% 
    gather(letter, value, -date) %>% 
    drop_na(value) %>% 
    group_nest(letter) %>%
    walk2(.x = .$letter,
          .y = .$data,
          .f = ~assign(.x, .y, envir = globalenv()))

Thanks @andresrcs! How I see the results of each data in the dataframe format?

Thanks again!

Can you elaborate on your question? I don't understand it.

Thanks @andresrcs! I see these new data sets A, B, C, D in the Values section but not in the Data section under Environment. I wanted to be able to view these data sets as dataframes. If I save x in a new variable also, I am not able to view them under Data section.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.