'determine number of instances of a category in R
This is my first time experimenting with R. I currently have a dataset called mydata that includes various categories. I need to somehow determine the number of ports that are equal to 80,443,25,993 out of all of the ports.
!
Solution 1:[1]
When posting a question here it's always helpful to have a sample of the data you're using. You can do this easily with dput(head(data_frame)). Since you didn't provide that I can demonstrate counting for a given condition with the built-in demo data frame called mtcars. Here is how you'd count the number of observations (i.e., rows) with a cyl value of 4 or 6:
sum(mtcars$cyl %in% c(4, 6))
This works because mtcars$cyl %in% c(4, 6) returns a vector of logical values for each observation. The vector contains TRUE values for the matches (i.e., where the cyl variable contains either a 4 or a 6) and FALSE values otherwise.
mtcars$cyl %in% c(4, 6)
[1] TRUE TRUE TRUE TRUE FALSE TRUE FALSE TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE TRUE TRUE TRUE
[29] FALSE TRUE FALSE TRUE
Since R treats TRUE as 1 and FALSE as zero you can sum these values to find a total count.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rdelrossi |
