【问题标题】:Simulation with Tidyverse -- putting data into tibble format使用 Tidyverse 进行模拟——将数据转换为 tibble 格式
【发布时间】:2020-05-18 22:26:57
【问题描述】:

我正在尝试使用 tidyverse 在 R 中运行模拟。此代码有效,但不能很好地扩展到多个变量。

关于如何改进这一点的任何想法?我试过purrr,但没有成功。

下面的示例从正态分布中提取 5 个值并重复此操作 3 次。我怎么能重复n 次而不是 3 次?

n = 5

x=1:n
y1 = rnorm(n)
y2 = rnorm(n)
y3 = rnorm(n)

# put data into tibble
df <- tibble(x=x, y1=y1, y2=y2, y3=y3)

# Tidy data -- go from wide to long
df <- pivot_longer(df, cols=starts_with('y'))

# Make plot
ggplot(df, aes(x=x, y=value, group=name, color=name))+
  geom_line()

【问题讨论】:

    标签: r simulation tidyr


    【解决方案1】:

    如果我们需要replicate,那么

    library(dplyr)
    library(tidyr)
    library(stringr)
    library(ggplot2)
    n <- 5
    rpl <- 3
    replicate(rpl, rnorm(n), simplify = FALSE) %>% 
          set_names(str_c('y', seq_along(.))) %>%
          as_tibble %>%
          mutate(x = row_number()) %>%
          pivot_longer(cols = starts_with('y')) %>%
          ggplot(aes(x=x, y=value, group=name, color=name))+       
            geom_line()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      • 2018-05-16
      • 2022-10-20
      • 2017-02-23
      • 2021-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多