【问题标题】:Create a sequence of values by group between a min and max interval using dplyr使用 dplyr 在最小和最大间隔之间按组创建值序列
【发布时间】:2019-12-20 07:08:32
【问题描述】:

这肯定是一个基本问题,但找不到解决方法。

我需要为每组 (fs) 的最小值 (dds_min) 到最大值 (dds_max) 创建一系列值。 这是我的数据:

fs <- c("early", "late")
dds_min <-as.numeric(c("47.2", "40"))
dds_max <-as.numeric(c("122", "105"))
dds_min.max <-as.data.frame(cbind(fs,dds_min, dds_max))

这就是我所做的......

dss_levels <-dds_min.max %>% 
                group_by(fs) %>% 
                mutate(dds=seq(dds_min,dds_max,length.out=100))

我打算创建一个新变量 (dds),它的长度必须为 100,并且根据“fs”以不同的值开始和结束。我的期望是以另一个数据框(dss_levels)结束,它有两列(fs 和 dds),上面有 200 个值。

但是我收到了这个错误。

Error: Column `dds` must be length 1 (the group size), not 100
In addition: Warning messages:
1: In Ops.factor(to, from) : ‘-’ not meaningful for factors
2: In Ops.factor(from, seq_len(length.out - 2L) * by) :
  ‘+’ not meaningful for factors

任何帮助将不胜感激。

谢谢!

【问题讨论】:

  • 不要使用as.data.frame(cbind(fs,dds_min, dds_max))cbind() 使所有内容成为矩阵,在转换为数据框之前将所有内容转换为character。如果直接使用data.frame(fs,dds_min, dds_max),没有问题。

标签: r dplyr


【解决方案1】:

为了便于说明,我将序列长度设为 5,您可以将其更改为 100。

library(purrr)
library(tidyr)
dds_min.max %>%
  mutate(dds= map2(dds_min, dds_max, seq, length.out = 5)) %>%
  unnest(cols = dds)
# # A tibble: 10 x 4
#    fs    dds_min dds_max   dds
#    <fct>   <dbl>   <dbl> <dbl>
#  1 early    47.2     122  47.2
#  2 early    47.2     122  65.9
#  3 early    47.2     122  84.6
#  4 early    47.2     122 103. 
#  5 early    47.2     122 122  
#  6 late     40       105  40  
#  7 late     40       105  56.2
#  8 late     40       105  72.5
#  9 late     40       105  88.8
# 10 late     40       105 105  

使用此数据(确保您的数字列是数字的!不要使用cbind!)

fs <- c("early", "late")
dds_min <-c(47.2, 40)
dds_max <-c(122, 105)
dds_min.max <-data.frame(fs,dds_min, dds_max)

【讨论】:

  • 非常感谢@Gregor!超级有用的答案。以前从未使用过map2unnest...需要探索一下这些功能的作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-28
  • 2018-11-15
  • 2015-12-02
相关资源
最近更新 更多