Starbucks Starbucks - 1 month ago 5x
R Question

Counting in R Using the Which Statement

I am trying to count the number of times text is in a column and using the which clause. So if I need to count all the "yes" in column A where column B has "France"

xx <- length(grep(da[which(da$fruit == "yes" & da$Q1 == "France")]))

Error in grep(da[which(da$fruit == "yes" & da$Q1 == "France")]) :
argument "x" is missing, with no default

Any help would be appreciated.

Thank you.


Your which statement doesn't need grep

xx <- length(which(da$fruit=="yes" & da$Q1=="France"))


> da

fruit      Q1
  no       France
  no       Spain
  yes      Spain
  yes      USA
  no       France
  yes      France
  no       USA
  yes      France

which(da$fruit=="yes" & da$Q1=="France")


> [1]  6  8

length(which(da$fruit=="yes" & da$Q1=="France"))


> [1] 2


Gives the TRUE indices of the object you are searching for.


Will give you the length of the vector of the TRUE indices. Therefore returns the count of the items that fit the criteria you provided.