Home > database >  Change column pattern R
Change column pattern R

Time:03-02

I don't know how to call the pattern of column but I have column like this

Gene         value1     value2
A              10          5
B              52         23
C              14          9

I want to change pattern of columns to be like this

Gene        Type       Value
A          value1        10      
A          value2         5
B          value1        52
B          value2        23
C          value1        14
C          value2         9

Mostly, in ggplot2 always apply this pattern of column in plotting so I am wondering how to write code in R

Thank you in advanced :D

CodePudding user response:

You can use pivot_longer from tidyr to put the data into long form.

library(tidyverse)

df %>% 
  pivot_longer(-Gene, names_to = "Type", values_to = "Value")

Output

  Gene  Type   Value
  <chr> <chr>  <int>
1 A     value1    10
2 A     value2     5
3 B     value1    52
4 B     value2    23
5 C     value1    14
6 C     value2     9

Or with data.table:

library(data.table)
dt <- as.data.table(df)

melt(dt, id.vars = "Gene", variable.name = "Type", value.name = "Value")

Data

df <- structure(list(Gene = c("A", "B", "C"), value1 = c(10L, 52L, 
14L), value2 = c(5L, 23L, 9L)), class = "data.frame", row.names = c(NA, 
-3L))

CodePudding user response:

For completeness, the desired transformation can also be obtained in base R with reshape function:

# Sample data
dta <- read.table(text = "Gene         value1     value2
A              10          5
B              52         23
C              14          9",  header = TRUE)

# Transformation
reshape(
    data = dta,
    direction = "long",
    idvar = "Gene",
    varying = c("value1", "value2"),
    v.names = "Value",
    timevar = "Type",
    times = c("value1", "value2")
)

Outcome

         Gene   Type Value
A.value1    A value1    10
B.value1    B value1    52
C.value1    C value1    14
A.value2    A value2     5
B.value2    B value2    23
C.value2    C value2     9
  •  Tags:  
  • r
  • Related