英文:
Reverse the content order of several columns (ideally in tidyverse)
问题
假设以下数据:
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 6 4 1
2 2 6 2 NA
3 3 6 NA NA
我考虑过使用 across
和 rev
的组合,但目前的尝试不起作用。
英文:
Assuming the following data:
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
And what I want is:
a b c d
1 1 6 4 1
2 2 6 2 NA
3 3 6 NA NA
I thought about some combination of across
and rev
, but my current attempts don't work.
答案1
得分: 3
以下是翻译好的代码部分:
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
英文:
You can do the following:
pivot_longer(df, -a) %>%
filter(!is.na(value)) %>%
mutate(value=rev(value), .by=a) %>%
pivot_wider(names_from = name, values_from = value)
Output:
a b c d
<int> <dbl> <dbl> <dbl>
1 1 6 4 1
2 2 6 2 NA
3 3 6 NA NA
答案2
得分: 2
A base R solution:
df[-1] <- t(apply(df[-1], 1, \(x) c(rev(x[complete.cases(x)]), x[is.na(x)])))
一个基本的R解决方案:
df[-1] <- t(apply(df[-1], 1, \(x) c(rev(x[complete.cases(x)]), x[is.na(x)])))
英文:
A base R solution:
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
答案3
得分: 1
首先定义一个目标列的向量,然后将非NA
值逐行粘贴到同一列中。然后将该列分开成宽格式。
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
英文:
First define a vector of target columns, then paste
the non-NA
values together into the same column row-wise. Then separate
that column to a wide format.
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论