简体   繁体   English

匹配和重新排序 R 中多列中的行(tidyverse)

[英]Match and re-order rows in multiple columns in R (tidyverse)

I have a dataset like this (in the actual dataset, I have more columns like subj01):我有一个这样的数据集(在实际数据集中,我有更多列,如 subj01):

# A tibble: 10 x 4
    item subj01 subj02 subj03
   <int>  <dbl>  <dbl>  <dbl>
 1     1      1      1      1
 2     2      2      2      6
 3     3      5      5      9
 4     4      9      6     NA
 5     5     10      8     NA
 6     6     NA      9     NA
 7     7     NA     10     NA
 8     8     NA     NA     NA
 9     9     NA     NA     NA
10    10     NA     NA     NA

I created the dataset using the code below.我使用下面的代码创建了数据集。

data = tibble(item = 1:10, subj01 = c(1,2,5,9,10,NA,NA,NA,NA,NA), subj02 = c(1,2,5,6,8,9,10,NA,NA,NA), subj03 = c(1,6,9,NA,NA,NA,NA,NA,NA,NA))

I would like to reorder all the columns beginning with "subj" so that the position of the values match that in the item column.我想重新排序所有以“subj”开头的列,以便值的 position 与项目列中的相匹配。

That is, for this example dataset, I would like to end up with this:也就是说,对于这个示例数据集,我想以这样的结尾:

# A tibble: 10 x 4
    item subj01 subj02 subj03
   <int>  <dbl>  <dbl>  <dbl>
 1     1      1      1      1
 2     2      2      2     NA
 3     3     NA     NA     NA
 4     4     NA     NA     NA
 5     5      5      5     NA
 6     6     NA      6      6
 7     7     NA     NA     NA
 8     8     NA      8     NA
 9     9      9      9      9
10    10     10     10     NA

I've figured that I can match and re-order one column by running this:我想我可以通过运行以下命令来匹配和重新排序一列:

data$subj01[match(data$item,data$subj01)]
 [1]  1  2 NA NA  5 NA NA NA  9 10

But I am struggling to apply this across multiple columns (ideally I'd like to embed the command in a dplyr pipe).但是我正在努力跨多个列应用它(理想情况下我想将命令嵌入到 dplyr 管道中)。

I tried the command below, but this gave me an error "Error in mutate(x. = x.[match(item, x.)]): object 'x.'我尝试了下面的命令,但这给了我一个错误“变异错误(x。= x。[匹配(项目,x。)]):object'x。' not found".未找到”。

data = data %>% across(mutate(x.=x.[match(item,x.)]))

I'd appreciate any suggestions.我将不胜感激任何建议。 Thank you.谢谢你。

library(tidyverse)
data %>%
  pivot_longer(-item) %>%
  filter(!is.na(value)) %>%
  mutate(item = value) %>%
  complete(item = 1:10, name) %>%
  pivot_wider(names_from = name, values_from = value)

# A tibble: 10 × 4
    item subj01 subj02 subj03
   <dbl>  <dbl>  <dbl>  <dbl>
 1     1      1      1      1
 2     2      2      2     NA
 3     3     NA     NA     NA
 4     4     NA     NA     NA
 5     5      5      5     NA
 6     6     NA      6      6
 7     7     NA     NA     NA
 8     8     NA      8     NA
 9     9      9      9      9
10    10     10     10     NA

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

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