Home > Mobile >  Remove NA from certain strings and glue it into one data.frame
Remove NA from certain strings and glue it into one data.frame

Time:11-17

I have a data frame

structure(list(col1 = 1:9, col2 = c(NA, 2L, 3L, 4L, 5L, 6L, 7L, 
8L, 9L), col3 = c(1L, 2L, NA, 4L, 5L, 6L, 7L, 8L, 9L), col4 = c(1L, 
2L, 3L, NA, 5L, 6L, 7L, 8L, 9L), col5 = c(1L, 2L, 3L, 4L, NA, 
6L, 7L, 8L, 9L), col6 = c(1L, 2L, 3L, 4L, 5L, NA, 7L, 8L, 9L), 
    col7 = c(1L, 2L, 3L, 4L, 5L, 6L, NA, 8L, 9L), col8 = c(1L, 
    2L, 3L, 4L, 5L, 6L, 7L, NA, 9L), col9 = c(1L, 2L, 3L, 4L, 
    5L, 6L, 7L, 8L, NA), col10 = 1:9), class = "data.frame", row.names = c(NA, 
-9L))

And I have a list

data_list <- list(c(1:3),c(4:6),c(7:10))

I would like to apply the na.omit function to the elements of this list in order.First apply the na.omit function to columns with(1:3), then with(4:6), and then with(7:10) and then join.

As a result, get such a data frame:

data<-structure(list(col1 = c(2L, 4L, 5L, 6L, 7L, 8L, 9L), col2 = c(2L, 
4L, 5L, 6L, 7L, 8L, 9L), col3 = c(2L, 4L, 5L, 6L, 7L, 8L, 9L), 
    col4 = c(1L, 2L, 3L, 7L, 8L, 9L, NA), col5 = c(1L, 2L, 3L, 
    7L, 8L, 9L, NA), col6 = c(1L, 2L, 3L, 7L, 8L, 9L, NA), col7 = c(1L, 
    2L, 3L, 4L, 5L, 6L, NA), col8 = c(1L, 2L, 3L, 4L, 5L, 6L, 
    NA), col9 = c(1L, 2L, 3L, 4L, 5L, 6L, NA), col10 = c(1L, 
    2L, 3L, 4L, 5L, 6L, NA)), class = "data.frame", row.names = c(NA, 
-7L))

CodePudding user response:

You will need to cbind not merge. There are a lot of functions that allow you to cbind unequal length data frames. You can find them here.

do.call(qpcR:::cbind.na, lapply(data_list, function(i)df[complete.cases(df[c(i)]),i]))

  col1 col2 col3 col4 col5 col6 col7 col8 col9 col10
2    2    2    2    1    1    1    1    1    1     1
4    4    4    4    2    2    2    2    2    2     2
5    5    5    5    3    3    3    3    3    3     3
6    6    6    6    7    7    7    4    4    4     4
7    7    7    7    8    8    8    5    5    5     5
8    8    8    8    9    9    9    6    6    6     6
9    9    9    9   NA   NA   NA   NA   NA   NA    NA
  • Related