简体   繁体   中英

Last two non-NA observations in row to front

I have a dataframe that looks like this

    A  B  F  B  J  R  8  4

    B  A  7  5  NA NA NA NA

    C  1  9  NA NA NA NA NA

I want to move the last two observations (excluding the NA) in each row to the front of the row. I tried to use subset() and dplyr package, but not able to figure it out yet.

So then it should look like

8  4  A  B  F  B  J  R

7  5  B  A  NA NA NA NA

1  9  C  NA NA NA NA NA

We can use apply row-wise and arrange the row in a way to get the indices of last two non-NA values and select the remaining indices.

df[] <- t(apply(df, 1, function(x) {
       inds <- tail(which(!is.na(x)), 2)
       c(x[inds], x[setdiff(seq_along(x), inds)])
}))

df
#  V1 V2 V3   V4   V5   V6   V7   V8
#1  8  4  A    B    F    B    J    R
#2  7  5  B    A  <NA> <NA> <NA> <NA>
#3  1  9  C  <NA> <NA> <NA> <NA> <NA>

data

df <- structure(list(V1 = structure(1:3, .Label = c("A", "B", "C"),
class = "factor"), V2 = structure(3:1, .Label = c("1", "A", "B"), 
class = "factor"), V3 = structure(c(3L, 1L, 2L), .Label = c("7", "9", "F"), 
class = "factor"),V4 = structure(c(2L, 1L, NA), .Label = c("5", "B"), 
class = "factor"), V5 = structure(c(1L, NA, NA), .Label = "J", class = "factor"), 
V6 = structure(c(1L, NA, NA), .Label = "R", class = "factor"), 
V7 = c(8L, NA, NA), V8 = c(4L, NA, NA)), class = "data.frame", 
row.names = c(NA, -3L))

We can do this with base R using head and tail

df[] <- t(apply(df, 1, function(x) `length<-`(c(tail(na.omit(x), 2), 
       head(na.omit(x), -2)), length(x))))
df
#   V1 V2 V3   V4   V5   V6   V7   V8
#1  8  4  A    B    F    B    J    R
#2  7  5  B    A <NA> <NA> <NA> <NA>
#3  1  9  C <NA> <NA> <NA> <NA> <NA>

data

df <- structure(list(V1 = c("A", "B", "C"), V2 = c("B", "A", "1"), 
    V3 = c("F", "7", "9"), V4 = c("B", "5", NA), V5 = c("J", 
    NA, NA), V6 = c("R", NA, NA), V7 = c(8L, NA, NA), V8 = c(4L, 
    NA, NA)), class = "data.frame", row.names = c(NA, -3L))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM