0

I am trying to manipulate this data frame:

df
   name     date     X  Y
Person1   Monday     1  5
Person2   Monday     2  6
Person1  Tuesday     3  7
Person2  Tuesday     4  8

To look like this:

   name   variable  Monday  Tuesday
Person1          X       1        3
Person1          Y       5        7
Person2          X       2        4
Person2          Y       6        8

Is there a way to manipulate my original data frame to get this result using R?

This was marked as a duplicate, but neither of the links provided solved my problem because I am not quite going from wide to long or long to wide.

Philip
  • 39
  • 1
  • 12
  • This was marked as a duplicate, but neither of the links provided solved my problem because I am not quite going from wide to long or long to wide. – Philip Dec 04 '18 at 14:26

2 Answers2

2

Here is a way with data.table

library(data.table)
dt <- fread(text)
dcast(melt(dt, id.vars = c('name', 'date')), name + variable ~ date)
#      name variable Monday Tuesday
#1: Person1        X      1       3
#2: Person1        Y      5       7
#3: Person2        X      2       4
#4: Person2        Y      6       8

data

text <- "name    | date    | X | Y
Person1 | Monday  | 1 | 5
Person2 | Monday  | 2 | 6
Person1 | Tuesday | 3 | 7
Person2 | Tuesday | 4 | 8"

text <- gsub("\\|", "", text)
markus
  • 25,843
  • 5
  • 39
  • 58
1

Try this, then check out R For Data Science for more details

library(tidyverse)

df %>% 
  gather(X, Y, key = variable, value = temp) %>% 
  spread(key = date, value = temp)
Jordo82
  • 796
  • 4
  • 14