【发布时间】:2019-08-08 16:11:38
【问题描述】:
我有一些样品已经过各种不同水质参数的测试。每个参数都有两列:一个值和关于该值的注释。我想将参数收集成长格式,但我想将关于它们的 cmets 保存在不同的列中。我尝试使用两个收集语句,但这并不能保留值和注释列之间的关系。
我知道评论栏总是紧挨着价值栏的右侧,但我不知道如何利用这一点。
library(tidyverse)
#> Warning: package 'tidyverse' was built under R version 3.5.2
#> Warning: package 'ggplot2' was built under R version 3.5.3
#> Warning: package 'tibble' was built under R version 3.5.2
#> Warning: package 'tidyr' was built under R version 3.5.3
#> Warning: package 'readr' was built under R version 3.5.3
#> Warning: package 'purrr' was built under R version 3.5.3
#> Warning: package 'dplyr' was built under R version 3.5.3
#> Warning: package 'stringr' was built under R version 3.5.2
#> Warning: package 'forcats' was built under R version 3.5.2
my_df <- tibble(time_taken = 1:4, a = seq(2, 8, by = 2), a_comment = rep("Comment about A!", 4), b = seq(-8, -2, by = 2), b_comment = rep("Comment about B?", 4))
my_df
#> # A tibble: 4 x 5
#> time_taken a a_comment b b_comment
#> <int> <dbl> <chr> <dbl> <chr>
#> 1 1 2 Comment about A! -8 Comment about B?
#> 2 2 4 Comment about A! -6 Comment about B?
#> 3 3 6 Comment about A! -4 Comment about B?
#> 4 4 8 Comment about A! -2 Comment about B?
my_attempt <- my_df %>%
gather(key = "key", value = "value", a, b) %>%
gather(key = "comment_key", value = "comment", a_comment, b_comment)
my_attempt
#> # A tibble: 16 x 5
#> time_taken key value comment_key comment
#> <int> <chr> <dbl> <chr> <chr>
#> 1 1 a 2 a_comment Comment about A!
#> 2 2 a 4 a_comment Comment about A!
#> 3 3 a 6 a_comment Comment about A!
#> 4 4 a 8 a_comment Comment about A!
#> 5 1 b -8 a_comment Comment about A!
#> 6 2 b -6 a_comment Comment about A!
#> 7 3 b -4 a_comment Comment about A!
#> 8 4 b -2 a_comment Comment about A!
#> 9 1 a 2 b_comment Comment about B?
#> 10 2 a 4 b_comment Comment about B?
#> 11 3 a 6 b_comment Comment about B?
#> 12 4 a 8 b_comment Comment about B?
#> 13 1 b -8 b_comment Comment about B?
#> 14 2 b -6 b_comment Comment about B?
#> 15 3 b -4 b_comment Comment about B?
#> 16 4 b -2 b_comment Comment about B?
desired <- tibble(time_taken = rep(1:4, 2),
variable = c(rep("a", 4), rep("b", 4)),
value = c(seq(2, 8, by = 2), c(seq(-8, -2, by = 2))),
comment = c(rep("Comment about a!", 4), rep("Comment about b?", 4)))
desired
#> # A tibble: 8 x 4
#> time_taken variable value comment
#> <int> <chr> <dbl> <chr>
#> 1 1 a 2 Comment about a!
#> 2 2 a 4 Comment about a!
#> 3 3 a 6 Comment about a!
#> 4 4 a 8 Comment about a!
#> 5 1 b -8 Comment about b?
#> 6 2 b -6 Comment about b?
#> 7 3 b -4 Comment about b?
#> 8 4 b -2 Comment about b?
由reprex package (v0.2.1) 于 2019 年 8 月 8 日创建
【问题讨论】: