假设以下数据:
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
我考虑过across和rev的组合,但是我目前的尝试不起作用。
across
rev
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
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
mdfafbf13#
首先定义一个目标列的向量,然后将paste非NA值一起按行放入同一列。然后将separate列转换为宽格式。
paste
NA
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
3条答案
按热度按时间hfwmuf9z1#
您可以执行以下操作:
输出:
klh5stk12#
碱R溶液:
mdfafbf13#
首先定义一个目标列的向量,然后将
paste
非NA
值一起按行放入同一列。然后将separate
列转换为宽格式。