Ecg
Ecg

Reputation: 942

Quick way of creating a long data frame for repeated values and variable characters

Is there a quick way of creating a data frame for this (4columns x 3060 rows)?

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...

So the head would look like this

> 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

I have many errors but started with this

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)

Upvotes: 1

Views: 63

Answers (2)

Ryan John
Ryan John

Reputation: 1430

Here's a sample answer:

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)
)

To add in your excel you can try something like this. Copy the excel column without the header.

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

Upvotes: 2

akrun
akrun

Reputation: 887501

We can use 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))

Upvotes: 2

Related Questions