I'm afraid I still don't understand your logic, and without a reproducible example, called a reprex (with a corrected "green apple " to "green apple") the only thing I can suggest is
# Original code
input = data.frame(Jan=c(1,0,1,0,1,1),Feb= c(1,1,0,0,0,1), Mar = c(1,0,0,0,1,0), Apr = c(0,0,0,1,1,1))
rownames(input) = c("green apple","orange","banana","green banana","plastic apple","rotten orange")
expected_output = data.frame(Jan=c(1,1,1),Feb=c(1,1,0),Mar=c(1,0,0), Apr=c(1,1,1))
rownames(expected_output) = c("apple","orange","banana")
# Show expected output
expected_output
#> Jan Feb Mar Apr
#> apple 1 1 1 1
#> orange 1 1 0 1
#> banana 1 0 0 1
# Revised
# Install, if necessary, and load the following libraries
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(magrittr)
library(stringr)
library(tibble)
# Style varies on which assignment operator to use, <- or =
# It doesn't matter so long as you're consistent
# I like to use <- when defining an object like "input"
# and = when defining an attribute; be consistent with spaces/no spaces around =
# Avoid rownames, make the data you want to filter part of a data frame or tibble column
input <- data.frame(fruit = c("green apple","orange","banana","green banana",
"plastic apple","rotten orange"), Jan=c(1,0,1,0,1,1),
Feb= c(1,1,0,0,0,1), Mar = c(1,0,0,0,1,0),
Apr = c(0,0,0,1,1,1), stringsAsFactors = FALSE
)
# show revised input
input
#> fruit Jan Feb Mar Apr
#> 1 green apple 1 1 1 0
#> 2 orange 0 1 0 0
#> 3 banana 1 0 0 0
#> 4 green banana 0 0 0 1
#> 5 plastic apple 1 0 1 1
#> 6 rotten orange 1 1 0 1
# categorize fruit
input <- input %>% mutate(type_fruit = word(fruit[], -1)) %>% select(type_fruit, everything())
# show revised input
input
#> type_fruit fruit Jan Feb Mar Apr
#> 1 apple green apple 1 1 1 0
#> 2 orange orange 0 1 0 0
#> 3 banana banana 1 0 0 0
#> 4 banana green banana 0 0 0 1
#> 5 apple plastic apple 1 0 1 1
#> 6 orange rotten orange 1 1 0 1
# summarize by month by fruit type
output <- input %>% group_by(type_fruit) %>% summarize(Jan = sum(Jan), Feb = sum(Feb), Mar = sum(Mar), Apr = sum(Apr))
# show revised output
output
#> # A tibble: 3 x 5
#> type_fruit Jan Feb Mar Apr
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 apple 2 1 2 1
#> 2 banana 1 0 0 1
#> 3 orange 1 2 0 1
# Doesn't match the expected output because you don't specify whether you want <lgl>
# or <int>, and I've assumed <int>
Created on 2019-01-09 by the reprex package (v0.2.1)