little_big_thoughts
little_big_thoughts

Reputation: 157

Get columns values count using r-script

I want to get the count of column values for Prod1

S#  Types         Product Name
--  -----         ------------
1   ["A","B","C"] Prod1
2   ["B","C"]     Prod1
3   ["A","C"]     Prod1
4   ["Z"]         Prod2

I want the output for Prod1 in this format(i.e. Count of each column value)

Prod1
-----
A B C
2 2 3

I will use this value to plot a graph. Need a pure r-script way to do this without any additional libraries (cause i will use this in PowerBI).

Upvotes: 0

Views: 97

Answers (1)

Onyambu
Onyambu

Reputation: 79318

library(tidyverse) 
dat%>%
     group_by(Product_Name)%>%
     mutate(Types=str_extract_all(Types,"\\w"))%>%
     summarise(s=list(table(unlist(Types))))%>%
     unstack(s~Product_Name)
$Prod1

A B C 
2 2 3 

$Prod2

Z 
1 

Using base R:

a=transform(dat,Types=gsub("[^,A-Za-z0-9]","",Types))
b=aggregate(Types~Product_Name,a,function(x)table(unlist(strsplit(unlist(x),","))))
unstack(rev(b))

$Prod1

A B C 
2 2 3 

$Prod2

Z 
1 

Upvotes: 3

Related Questions