Muhammad Murtaza
Muhammad Murtaza

Reputation: 13

Adding character values of a column in R

I have two columns i.e. square_id & Smart_Nsmart as given below. I want to count(add) N's and S's against each square_id and ggplot the data i.e. plot square_id vs Smart_Nsmart.

square_id 1 1 2 2 2 2 3 3 3 3 Smart_Nsmart S N N N S S N S S S

Upvotes: 1

Views: 128

Answers (2)

Mahdi Baghbanzadeh
Mahdi Baghbanzadeh

Reputation: 548

The above answer is very smart. However, instead of count function, you can implement group_by and summarise just in case in future you want to apply some other functions to your code.

library(dplyr)
library(ggplot2)

dff <- data.frame(a=c(1,1,1,1,2,1,2),b=c("C","C","N","N","N","C","N"))

dff %>% 
group_by(a,b) %>% 
summarise(n = length(b) ) %>%
  ggplot(., aes(x= a, y = n, fill = b)) + 
  geom_bar(stat = 'identity')

Upvotes: 0

akrun
akrun

Reputation: 887501

We can use count and then use ggplot to plot the frequency. Here, we are plotting it with geom_bar (as it is not clear from the OP's post)

library(dplyr)
library(ggplot2)
df %>% 
   count(square_id, Smart_Nsmart) %>%
   ggplot(., aes(x= square_id, y = n, fill = Smart_Nsmart)) + 
         geom_bar(stat = 'identity')

Upvotes: 1

Related Questions