简体   繁体   English

是否有更有效或更简洁的方法来使用 tidyr::gather 使我的数据看起来“整洁”?

[英]Is there more efficient or concise way to use tidyr::gather to make my data look 'tidy'?

I am new to using tidyverse.我是使用 tidyverse 的新手。 I want to see if I am being as efficient/concise as possible using the functions in this package.我想看看我是否尽可能高效/简洁地使用此 package 中的功能。 I suspect I am not.我怀疑我不是。

My original data has the key sym as part of each column name.我的原始数据将密钥符号作为每个列名的一部分。

   day         a_x        b_x        a_y         b_y
1    1 -0.56047565  1.2240818 -1.0678237  0.42646422
2    2 -0.23017749  0.3598138 -0.2179749 -0.29507148
...

I would like to make the data look tidy, like so:我想让数据看起来整洁,如下所示:

     day sym         x      y
 1     1 a      0.118   0.702
 2     2 a     -0.947  -0.262
...
11     1 b      1.44    0.788
12     2 b      0.452   0.769

Here is my code that does the above transformations:这是我进行上述转换的代码:

library(tidyverse)
set.seed(123)

# example original table
d <- tibble(day=1:10,a_x=rnorm(10),b_x=rnorm(10),a_y=rnorm(10),b_y=rnorm(10))

# manipulations
d1 <- gather(d,a_x,b_x,key='sym',value='x') %>% mutate(sym=sub('_x','',sym)) %>% select(day,sym,x)
d2 <- gather(d,a_y,b_y,key='sym',value='y') %>% mutate(sym=sub('_y','',sym)) %>% select(day,sym,y)
d <- d1 %>% full_join(d2,by=c('day','sym'))

What would be a better way to use some of the tidyverse functions to to achieve the same result in fewer lines or more efficiently?使用一些 tidyverse 函数以更少的行或更有效地实现相同结果的更好方法是什么?

Thanks!谢谢!

gather has been retired in favor of pivot_longer which makes such transformation simpler. collect 已被pivot_longer gather这使得这种转换变得更简单。

tidyr::pivot_longer(d, cols = -day, 
                    names_to = c('sym', '.value'), names_sep = '_')

# A tibble: 20 x 4
#    day sym        x      y
#* <int> <chr>  <dbl>  <dbl>
#1     1 a     -0.560 -1.07 
#2     1 b      1.22   0.426
#3     2 a     -0.230 -0.218
#4     2 b      0.360 -0.295
#...
#...

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

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