Starbucks Starbucks - 2 months ago 7
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.

Answer

Your which statement doesn't need grep

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

ex.)

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

Returns:

> [1]  6  8

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

Returns:

> [1] 2

which(): https://stat.ethz.ch/R-manual/R-devel/library/base/html/which.html

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

length(): https://stat.ethz.ch/R-manual/R-devel/library/base/html/length.html

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.