颠倒几个列的内容顺序(理想情况下在Tidyverse中)

vsnjm48y  于 2023-06-03  发布在  其他
关注(0)|答案(3)|浏览(152)

假设以下数据:

df <- data.frame(a = 1:3, b = c(1, 2, 6), c = c(4, 6, NA), d = c(6, NA, NA))

  a b  c  d
1 1 1  4  6
2 2 2  6 NA
3 3 6 NA NA

我想要的是

a b  c  d
1 1 6  4  1
2 2 6  2 NA
3 3 6 NA NA

我考虑过acrossrev的组合,但是我目前的尝试不起作用。

hfwmuf9z

hfwmuf9z1#

您可以执行以下操作:

pivot_longer(df, -a) %>%
  filter(!is.na(value)) %>%
  mutate(value=rev(value), .by=a) %>%
  pivot_wider(names_from = name, values_from = value)

输出:

a     b     c     d
  <int> <dbl> <dbl> <dbl>
1     1     6     4     1
2     2     6     2    NA
3     3     6    NA    NA
klh5stk1

klh5stk12#

碱R溶液:

df[-1] <- t(apply(df[-1], 1, \(x) c(rev(x[complete.cases(x)]), x[is.na(x)])))

  a b  c  d
1 1 6  4  1
2 2 6  2 NA
3 3 6 NA NA
mdfafbf1

mdfafbf13#

首先定义一个目标列的向量,然后将pasteNA值一起按行放入同一列。然后将separate列转换为宽格式。

library(tidyverse)

target_cols <- c("b", "c", "d")

df %>% 
  rowwise() %>% 
  mutate(concat = paste0(rev(na.omit(c_across(all_of(target_cols)))), collapse = ","), .keep = "unused") %>% 
  separate_wider_delim(cols = concat, names = target_cols, delim = ",", too_few ="align_start")

# A tibble: 3 × 4
      a b     c     d    
  <int> <chr> <chr> <chr>
1     1 6     4     1    
2     2 6     2     NA   
3     3 6     NA    NA

相关问题