r-为重复值和可变字符创建长数据帧的快速方法



有没有一种快速的方法可以为此创建数据帧(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)

下面是一个示例答案:

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列。

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

我们可以使用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))

最新更新