【问题标题】:Create R code to re-create a data.frame or tibble that I have in memory创建 R 代码以重新创建内存中的 data.frame 或 tibble
【发布时间】:2022-11-30 14:52:30
【问题描述】:

我正在尝试生成一些创建 data.frame(或 tibble)的 R 代码。例如。像这样:

library(tidyverse)
example_data <- tibble(`Letter number`=1:10, Letter=letters[1:10])

IE。无需创建加载的 .csv 或 .rds 文件。这是一些培训材料(使用 R markdown 创建的独立 html 文件),人们可以从中复制一些代码并将其粘贴到他们的 R 编辑器/RStudio 会话中。我想提供一个小示例数据集以供练习使用。

假设我已经在我的计算机上创建了我想要的数据集(例如,使用制表器从 pdf 中读取表格,各种处理等),现在想要创建像上面那样的代码,以便能够将此代码复制并粘贴到.Rmd 用于生成 html 文件。有没有像

create_code_to_generate_tibble( example_data ) 

那会输出第一个代码块(减去库加载)?

【问题讨论】:

  • 请查看dput(example_data)的输出
  • 谢谢 dput 确实非常接近我想要的。

标签: r dataframe tibble


【解决方案1】:

也许是这样的?

example_data = structure(list(`Letter number` = 1:10, Letter = c("a", "b", "c", 
"d", "e", "f", "g", "h", "i", "j")), class = c("tbl_df", "tbl", 
"data.frame"), row.names = c(NA, -10L))


> example_data
# A tibble: 10 x 2
   `Letter number` Letter
             <int> <chr> 
 1               1 a     
 2               2 b     
 3               3 c     
 4               4 d     
 5               5 e     
 6               6 f     
 7               7 g     
 8               8 h     
 9               9 i     
10              10 j   

【讨论】:

    【解决方案2】:

    我认为您采用的是一种更自动化的方式,但是可以生成手动创建的数据框并进行填充,例如:

    # collection of months (initially empty)
    months <- data.frame(
      start_date = character(),
      label = character(),
      stringsAsFactors = FALSE
    )
    # manually add months with start date, and label
    # generate these lines from CSV or Excel for example
    months[1L, ] <- c("1/Aug/2022", "August 2022")
    months[2L, ] <- c("1/Sep/2022", "September 2022")
    months[3L, ] <- c("1/Oct/2022", "October 2022")
    months[4L, ] <- c("1/Nov/2022", "November 2022")
    

    我发现像这样按行工作相当线性且易于解释。

    【讨论】:

      猜你喜欢
      • 2013-10-14
      • 1970-01-01
      • 2019-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多