Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何使用ggplot2打印有效行数_R_Ggplot2_Count - Fatal编程技术网

R 如何使用ggplot2打印有效行数

R 如何使用ggplot2打印有效行数,r,ggplot2,count,R,Ggplot2,Count,使用数据帧作为 df <- data.frame(name = c("a", "b", "c", "d", "e"), class = c("a1", "a1", "a1", "b1", "b1"), var1 = c("S", "S", "R", "S", "S"), var2 = c("S", "R", NA, NA, "R"), var3 = c(NA, "R", "R", "S"

使用数据帧作为

df <- data.frame(name = c("a", "b", "c", "d", "e"),
             class = c("a1", "a1", "a1", "b1", "b1"),
             var1 = c("S", "S", "R", "S", "S"),
             var2 = c("S", "R", NA, NA, "R"),
             var3 = c(NA, "R", "R", "S", "S"))
df_count <- matrix(nrow=3, ncol=2)
df_count <- as.data.frame(df_count)
names(df_count) <- c("var_num", "count")
df_count$var_num <- as.factor(names(df)[3:5])
for (i in 1:3) {
    df_count[i,2] <- sum(!is.na(df[,i+2]))
}
有没有一种更简单的方法可以选择var1到var3,并在不生成新数据帧的情况下计算有效行数?

library('ggplot2'))
library('ggplot2')
library('reshape2')

df <- melt(df, id.vars = c('name', 'class'))  # melt data
df <- df[!is.na(df$value), ]                  # remove NA
df <- with(df, aggregate(df, by = list(variable), FUN = length )) # compute length by grouping variable

ggplot(df, aes( x = Group.1, y = value, fill = Group.1 )) + 
   geom_bar(stat="identity")
库('reformae2')
df不管怎样,您都需要将形状改为长形,但是
geom_bar
stat_count
可以为您聚合,例如
库(tidyverse);df%%>%聚集(var,val,以('var')开始)%%>%drop\u na(val)%%>%ggplot(aes(var,fill=val))+geom\u bar()
library('ggplot2')
library('reshape2')

df <- melt(df, id.vars = c('name', 'class'))  # melt data
df <- df[!is.na(df$value), ]                  # remove NA
df <- with(df, aggregate(df, by = list(variable), FUN = length )) # compute length by grouping variable

ggplot(df, aes( x = Group.1, y = value, fill = Group.1 )) + 
   geom_bar(stat="identity")
df <- melt(df, id.vars = c('name', 'class'))  # melt data
df <- df[!is.na(df$value), ]                  # remove NA
df <- with(df, aggregate(df, by = list(variable, value), FUN = length )) # compute length by grouping variable and value

ggplot(df, aes( x = Group.1, y = value, fill = Group.2 )) + 
  geom_bar(stat="identity")
df <- data.frame(name = c("a", "b", "c", "d", "e"),
                 class = c("a1", "a1", "a1", "b1", "b1"),
                 var1 = c("S", "S", "R", "S", "S"),
                 var2 = c("S", "R", NA, NA, "R"),
                 var3 = c(NA, "R", "R", "S", "S"))