transfer empty spaces from the database to the last column in the R

Asked

Viewed 31 times

1

Good afternoon

To help me with the problem I set up a fictitious database

dados1<-c(15,15,16,17,18,52,48,47,65,32,'',15,14)
dados2<-c(15,15,16,17,18,52,'',47,65,32,15,15,14)
dados3<-rbind(dados1,dados2)
dados3<-data.frame(dados3)

where the result of data3 is as follows:

         X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 X11 X12 X13
  dados1 15 15 16 17 18 52 48 47 65  32      15  14
  dados2 15 15 16 17 18 52    47 65  32  15  15  14

need to transfer the empty spaces to the last column, that is to join the base, leaving empty spaces in the last column

  • I would pass each row to one vector, delete the empty vector, and stack again. But it’s a pretty naive solution. If no one responds in a week, send me a warning here, I’ll try

  • Empty spaces can be interpreted as NA? If first empty space (X7, dates2) goes to the last column, who should occupy that slot? Describe a little more about the constraints of the problem.

1 answer

3


This solution assumes that the data should be numerical but with the value '' have become characters or factors.
So first they turn into numbers, which makes the '' stay NA.

dados3[] <- lapply(dados3, function(x) as.numeric(as.character(x)))

Now, I will work with a copy. In your case you can change this and the instruction apply.

dados3b <- dados3
dados3b <- t(apply(dados3b, 1, function(x){
  if(anyNA(x)){
    n <- length(x)
    na <- which(is.na(x[-n]))
    for(i in na){
      x[i:(n - 1)] <- x[(i + 1):n]
      is.na(x) <- n
    }
  }
  x
}))

dados3b <- as.data.frame(dados3b)
dados3b
#        X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 X11 X12 X13
#dados1  15 15 16 17 18 52 48 47 65  32  15  14  NA
#dados2  15 15 16 17 18 52 47 65 32  15  15  14  NA
#dados2a 15 15 16 17 18 52 47 65 32  15  15  14  NA

Dice.

To test the above code I created another vector, with '' in last position.

dados1 <- c(15,15,16,17,18,52,48,47,65,32,'',15,14)
dados2 <- c(15,15,16,17,18,52,'',47,65,32,15,15,14)
dados2a <- c(15,15,16,17,18,52,47,65,32,15,15,14,'')
dados3 <- rbind(dados1, dados2, dados2a)
dados3 <- data.frame(dados3)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.