ss sss
ss sss

Reputation: 75

How to use regex for ifelse tidyverse

My df is as followed

monday_A    monday_B     tuesday_A    tuesday_B
1                2               4    100
6                7               8    5

I want to reorder this so it becomes

date       Group    quantitive
Monday     A        1
Monday     A        6
Monday     B        2
Monday     B        7
Tuesday    A        4
Tuesday    A        8
Tuesday    B        100
Tuesday    B        5

What i've done

 df %>% pivot_longer(monday_A:tuesday_B, names_to="tempGroup", values_to="quantitive") 

This made it

tempGroup    quantitive
monday_A     1
monday_A     6
monday_B     2
monday_B     7
tuesday_A    4
tuesday_A    8
tuesday_B    100
tuesday_B    5

Now how do I separate tempgroup ? I think regex by ifelse could do it by separating the undercore

Upvotes: 1

Views: 41

Answers (2)

hello_friend
hello_friend

Reputation: 5788

Base R Solution:

# Transpose dataframe matrix: tpd => as.data.frame
tpd <- as.data.frame(t(df))

# Restructure the dataframe into the desired format: df_td => data.frame 
df_td <-
  data.frame(
    day = gsub("_.*", "", rep(row.names(tpd), ncol(tpd))),
    group = gsub(".*_", "", rep(row.names(tpd), ncol(tpd))),
    quantitative = unlist(tpd),
    row.names = NULL
  )

Data

# Create re-usable data: df =>  data.frame
df <-
  structure(
    list(
      monday_A = c(1L, 6L),
      monday_B = c(2L, 7L),
      tuesday_A = c(4L,
                    8L),
      tuesday_B = c(100L, 5L)
    ),
    row.names = c(NA,-2L),
    class = "data.frame"
  )

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388972

Use names_sep :

tidyr::pivot_longer(df, cols = everything(), 
                    names_sep = "_",
                    names_to= c("date", "tempGroup"), 
                    values_to="quantitative")

# A tibble: 8 x 3
#  date    tempGroup quantitative
#  <chr>   <chr>          <int>
#1 monday  A                  1
#2 monday  B                  2
#3 tuesday A                  4
#4 tuesday B                100
#5 monday  A                  6
#6 monday  B                  7
#7 tuesday A                  8
#8 tuesday B                  5

data

df <- structure(list(monday_A = c(1L, 6L), monday_B = c(2L, 7L), 
tuesday_A = c(4L, 8L), tuesday_B = c(100L, 5L)), 
class = "data.frame", row.names = c(NA, -2L))

Upvotes: 2

Related Questions