简体   繁体   English

从行到前的最后两个非 NA 观测值

[英]Last two non-NA observations in row to front

I have a dataframe that looks like this我有一个看起来像这样的 dataframe

    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.我想将每行中的最后两个观察值(不包括 NA)移到行的前面。 I tried to use subset() and dplyr package, but not able to figure it out yet.我尝试使用子集()和 dplyr package,但还没有弄清楚。

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.我们可以使用逐行apply并以某种方式排列行以获取最后两个非 NA 值的索引和 select 剩余索引。

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我们可以使用headtail使用base R来做到这一点

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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