Home > OS >  How do I organize this data so that each ID has one row, and each Action has one column for Daily Co
How do I organize this data so that each ID has one row, and each Action has one column for Daily Co

Time:12-04

My dataset is:

ID Action Daily_Contact
760 Email 5
760 Text 4
760 Phone call 7
430 Phone call 2
430 Email 9
430 Text 8

and I want it to look like this,

ID Email Text PhoneCall
760 5 4 7
430 9 8 2

CodePudding user response:

Next time, please copy and paste the output of dput(df) so it is easier to replicate. Here is a tidyverse solution.

df <- data.frame(id=c(760,760,760,430,430,430),
                 action=c("email","text","phone","phone","email","text"),
                 daily_contact=c(5,4,7,2,9,8))


df %>%
  group_by(id) %>%
  pivot_wider(names_from = action, values_from = daily_contact)

EDIT: TarJae's comment is correct. It works for me too.

df %>%
  pivot_wider(names_from = action, values_from = daily_contact)

CodePudding user response:

You can use data.table

library(data.table)

dt <- data.table(id, action, Daily_Contact)

dcast(dt, id ~ action, value.var = "Daily_Contact")

##    id Email Phone call Text
## 1: 430     9          2    8
## 2: 760     5          7    4
  • Related