0

I have looked around for what I thought would be a simple solution, but nothing has proven helpful so far. Here is what I'd like to do:

1) Separately count the total number of 3 different strings in a specific data frame column, 2) put those 3 counts into a new vector, 3) add that vector to another data frame. Here is what I've tried:

> x <- c("Type1", "Type1", "Type2", "Type2")
> Column_Counts <- table(x)
> Type_One <- Column_Counts[names(Column_Counts)=="Type1"]
> Type_One <- as.numeric(Type_One)
> Type_Two <- Column_Counts[names(Column_Counts)=="Type2"]
> Type_Two <- as.numeric(Type_Two)
> Type_Three <- Column_Counts[names(PS_Count)=="Type3"]
> Type_Three <- as.numeric(Type_Three)
> New_Vector <- c(Type_One, Type_Two, Type_Three)

Here's the problem: sometimes "Type3" doesn't show up in my report, and if so I need it to be counted as zero, but Type_Three has value "numeric (empty)" and doesn't get added to the new vector.

> New_vector
[1] 2 2
#I need New_vector to be [1] 2, 2, 0

I need Type_Three to = 0, not "numeric (empty)". Here is what I tried:

> if (Type_Three == "(empty)")
{Type_Three <- 0}
#Error in if (CR_Des == "(empty)") { : argument is of length zero

Also:

> if (length(Type_Three == 0)
{Type_Three <- 0}
#This does nothing, even though the length is 0.

Any help is greatly appreciated.

Tunn
  • 1,506
  • 16
  • 25
  • Please submit a minimal _reproducible_ example. See: [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – Eric Fail Jan 21 '16 at 22:20
  • Look at the optional parameters of the `table` function. You might need useNA = "always", but it's not at all clear without a specific (simple, small) example. And note that testing for R NA values with "==" is not going to be productive. – IRTFM Jan 21 '16 at 22:26
  • Please check the examples of `?table`; i.e. `d <- factor(rep(c("A","B","C"), 10), levels = c("A","B","C","D","E"))`. – Henrik Jan 21 '16 at 22:38
  • 2
    No need to subset the result from `table` for each desired string. A toy example: `x <- factor(c("a", "b", "a", "c"), levels = letters[1:4])`; `my_x <- c("a", "b", "d")`; `table(x)`; `table(x)[my_x]` – Henrik Jan 21 '16 at 22:44
  • @Henrik, you should post your comment as an answer :) – Alexander Radev Jan 21 '16 at 23:08
  • 1
    I edited to include a minimal reproducible example (@Eric Fail, @42) and made my specific issue more clear. Couldn't get the factor to work, and tried the other answer [(http://stackoverflow.com/questions/1617061/including-missing-values-in-table-results-in-r)] @Henrik. Hopefully it makes more sense now with edits to my OP. – Tunn Jan 22 '16 at 15:01
  • Ok figured it out... instead of 'if (length(Type_Three == 0)) {Type_Three < 0}' it's 'if (length(Type_Three) == 0)' – Tunn Jan 22 '16 at 15:19

0 Answers0