将 R 中特定列的值向右移动

问题描述 投票:0回答:1

我想将特定列的值向右移动,并将 NA 保留在左侧。

df = data.frame(a = c("one", "two", "three", "four", "five"), 
                x = c("l", "m", NA, NA, "p"),
                y = c(NA, "b", "c", NA, NA),
                z = c("u", NA, "w", "x", "y"))

      a    x    y    z
1   one    l <NA>    u
2   two    m    b <NA>
3 three <NA>    c    w
4  four <NA> <NA>    x
5  five    p <NA>    y

这就是我想要的输出

   a      x     y     z
1  one   <NA>   l    u
2  two   <NA>   m    b 
3  three <NA>   c    w
4  four  <NA> <NA>   x
5  five  <NA>   p    y
r dataframe function na
1个回答
0
投票

您可以在

apply
上执行逐行
df
(不包括第一列),将
c
与非
NA
条目组合(通过
NA
)。然后
na.omit
使用您的第一列,并进一步塑造成您想要的数据框输出。
cbind

© www.soinside.com 2019 - 2024. All rights reserved.