user330
user330

Reputation: 1270

How to stack raw and creating a new variable in R

Here is a small sample of my data

AB  AN  AQ  AP  AA
1   O1  N   12  13
2   K1  B   22  16

I want to generate this table

AB  AN  AQ  New AP
1   O1  N   1   12
1   O1  N   2   13
2   K1  B   1   22
2   K1  B   2   16

The logic is to stack the same data in AB, AN and AQ next generate a new colour which gets 1 and then AP. Under this raw, the same data but the New column get 2 and then AA. So the new column is 1 and 2

Upvotes: 1

Views: 68

Answers (2)

akrun
akrun

Reputation: 887153

An option with reshape from base R

names(df)[4:5] <- paste0("AP", 1:2)
reshape(df, direction = "long", varying = 4:5, sep= "", timevar = "New")
#    AB AN AQ New AP id
#1.1  1 O1  N   1 12  1
#2.1  2 K1  B   1 22  2
#1.2  1 O1  N   2 13  1
#2.2  2 K1  B   2 16  2

data

df <- structure(list(AB = 1:2, AN = c("O1", "K1"), AQ = c("N", "B"), 
    AP = c(12L, 22L), AA = c(13L, 16L)), 
class = "data.frame", row.names = c(NA, -2L))

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

You can get the data in long format and then generate a new column based on unique column values.

library(dplyr)
library(tidyr)

df %>%
  pivot_longer(cols = c(AP, AA), 
               values_to = 'AP', 
               names_to = 'New') %>%
  mutate(New = match(New, unique(New)))

#     AB AN    AQ      New    AP
#  <int> <chr> <chr> <int> <int>
#1     1 O1    N         1    12
#2     1 O1    N         2    13
#3     2 K1    B         1    22
#4     2 K1    B         2    16

data

df <- structure(list(AB = 1:2, AN = c("O1", "K1"), AQ = c("N", "B"), 
    AP = c(12L, 22L), AA = c(13L, 16L)), 
class = "data.frame", row.names = c(NA, -2L))

Upvotes: 1

Related Questions