【问题标题】:Quick way of creating a long data frame for repeated values and variable characters为重复值和可变字符创建长数据框的快速方法
【发布时间】:2020-04-14 20:45:29
【问题描述】:

有没有一种快速的方法可以为此创建一个数据框(4 列 x 3060 行)?

Column 1: Repeating (1:17) until row 3060
Column 2: Repeating: (6x"W", 5x"M", 6x"E")like this: (W, W, W, W, W, W, M, M, M, M, M, E, E, E, E, E, E) until row 3060
Column 3: (A1x17rows, A2x17 rows....) for this this:  A1:A27, B1:B92, C1:C61) 
Column 4: Values ( I can copy form an excel sheet) ie: 0.06,0.03...

所以头部看起来像这样

> head(df)
  Column1 Column2 Column3 Column4
1       1       W      A1  0.0060
2       2       W      A2  0.0030
3       3       W      A3  0.0120
4       4       W      A4  0.0238
5       5       W      A5  0.0020
6       6       W      A6  0.0040

我有很多错误,但从这个开始

Column1 = c(1:17)
Column2 =c(6x"W", 5x"M",6x"E")
Column3 = c("A1":"A27"...)
Column4 = c("Values")

df <- data.frame(Column1, Column2, Column3, Column4)

【问题讨论】:

  • 我认为扩展值将超过 2060
  • @akrun 3060 很抱歉 ;)

标签: r dataframe multiple-columns


【解决方案1】:

这是一个示例答案:

library(tidyverse)
df <- tibble::tibble(
  ID = 1:3060, #use this to sort
  column1 = rep(1:17,180),
  column2 = rep(c(rep("W",6),rep("M",5),rep("E",6) ), 180),
  column3 = rep(c(paste0("A",rep(1:27)), paste0("B",rep(1:92)), paste0("C",rep(1:61))),17)
)

要添加到您的 Excel 中,您可以尝试这样的方法。复制没有标题的excel列。

column4 <- read_table(clipboard())
df %>%  bind_cols(column4)

【讨论】:

  • 有没有办法添加列所以我有 A1x17, A2x17... A27x17 其他... Column5 = rep(c(rep("A1",17),rep("A2" ,17).....rep("A27",17)))))
  • 该列实际上可能只是数字 1x17、2x17.... 直到 27x17
  • 与此相关,在另一个df上但相关:如果n = 92(其中Z1x17,..Z92x17,除了Column = rep(c(rep(“ Z1",17),rep("Z2",17),rep("Z3",17),rep("Z4",17),..., rep("Z92",17) ?
  • 类似这样的东西:rep(paste0("Z", 1:6),17) %&gt;% str_sort() %&gt;% head(92)
【解决方案2】:

我们可以使用crossing

library(dplyr)
library(tidyr)  
crossing(col1 = 1:17, col3 = c(paste0("A", 1:27), paste0("B", 1:92), paste0("C", 1:61))) %>% 
      mutate(col2 = rep(c("W", "M", "E"), length.out = 3060))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-15
    • 2011-02-05
    • 1970-01-01
    • 2015-05-13
    相关资源
    最近更新 更多