简体   繁体   English

在 R 中添加列的字符值

[英]Adding character values of a column in R

I have two columns ie square_id & Smart_Nsmart as given below.我有两列,即 square_id 和 Smart_Nsmart,如下所示。 I want to count(add) N's and S's against each square_id and ggplot the data ie plot square_id vs Smart_Nsmart.我想对每个square_id 和ggplot 数据计算(添加)N 和S,即绘制square_id 与Smart_Nsmart。

square_id 1 1 2 2 2 2 3 3 3 3 Smart_Nsmart SNNNSSNSSS square_id 1 1 2 2 2 2 3 3 3 3 Smart_Nsmart SNNNSSNSSS

We can use count and then use ggplot to plot the frequency.我们可以使用count然后使用ggplot来绘制频率。 Here, we are plotting it with geom_bar (as it is not clear from the OP's post)在这里,我们用geom_bar绘制它(因为从 OP 的帖子中不清楚)

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

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.然而,不是count功能,可以实现group_bysummarise ,以防万一将来你想一些其他的功能,适用于你的代码。

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM