简体   繁体   English

在 r 中一次收集多个列

[英]Gather serveral columns at once in r

I am trying to gather() a data.frame, but somehow it is not doing what I want.我正在尝试gather()一个 data.frame,但不知何故它没有做我想要的。 This is my data:这是我的数据:

df <- data.frame("id" = c(1),
                 "reco_1"= c(2),
                 "sim_1" = c(2),
                 "title_1"= c(2),
                 "reco_2" = c(3),
                 "sim_2" = c(3),
                 "title_2"= c(3))

And this is what it looks like printed:这就是打印出来的样子:

> df
  id reco_1 sim_1 title_1 reco_2 sim_2 title_2
1  1      2     2       2      3     3       3

When I now gather() my df, it looks like this:当我现在gather()我的 df 时,它看起来像这样:

> df %>% gather(reco, sim, -id)
  id    reco sim
1  1  reco_1   2
2  1   sim_1   2
3  1 title_1   2
4  1  reco_2   3
5  1   sim_2   3
6  1 title_2   3

However, what I would like to have is the following structure:但是,我想要的是以下结构:

  id  reco  sim  title
1  1  2     2    2
2  2  3     3    3

I would appreciate any help, since I do not even know whether gather() is even the right verb for it.我会很感激任何帮助,因为我什至不知道gather()是否是正确的动词。

We can use pivot_longer我们可以使用pivot_longer

library(dplyr)
library(tidyr)
df %>% 
  pivot_longer(-id, names_to = c(".value", "new_id"), names_sep = "_") %>% 
  select(-id)

# A tibble: 2 x 4
  new_id  reco   sim title
  <chr>  <dbl> <dbl> <dbl>
1 1          2     2     2
2 2          3     3     3

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

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