Table() with which() statement

rstudio

#1

Hello,

I am having a data set with a mixed of positive and positive number.

Can I use table() command to give me an output of how many data that have negative values and how many have positive value?
I tried one and I have an error message.

> table(final_df$Gross_MarginDollars_Percentage(which[final_df$Gross_MarginDollars_Percentage < '0'],))

Error in table(final_df$Gross_MarginDollars_Percentage(which[final_df$Gross_MarginDollars_Percentage <  : 
  attempt to apply non-function

#2

which(final_df$Gross_MarginDollars_Percentage < 0) gives you the indexes of the values in final_df$Gross_MarginDollars_Percentage that are less than zero. (Note that you don't want to put 0 in quotes!)

To just get a table of counts for a logical condition as applied to a vector, try:

table(final_df$Gross_MarginDollars_Percentage < 0)

Example:

df <- data.frame(
  x = rnorm(100)
)

which(df$x < 0)
#>  [1]  1  2  4  5  9 11 13 14 18 21 23 25 29 30 33 34 35 37 38 40 42 43 44
#> [24] 48 49 50 51 53 55 57 59 60 61 64 66 67 71 72 77 78 80 81 83 84 85 88
#> [47] 89 90 91 94 96

df$x[df$x < 0]
#>  [1] -0.27555608 -1.14022755 -0.10568973 -0.48410662 -0.14562143
#>  [6] -0.04536509 -1.10255446 -0.09387260 -1.33332934 -0.52829438
#> [11] -0.45665006 -1.03206253 -0.38032971 -0.18437594 -1.16961688
#> [16] -0.92645768 -0.32982780 -0.51697968 -0.66747567 -0.59741978
#> [21] -0.49793554 -0.77458899 -1.97636936 -1.03779073 -0.05524230
#> [26] -0.40568059 -0.94355835 -0.22429931 -0.43200052 -1.70511108
#> [31] -1.86829100 -0.62248846 -0.16135695 -0.38743952 -1.00159625
#> [36] -1.31691048 -1.22862499 -0.99497821 -1.27434571 -2.03293025
#> [41] -2.01034921 -0.71277968 -0.68596871 -2.26772365 -0.95920577
#> [46] -1.49370209 -0.29099755 -0.12280821 -1.33242681 -0.62586296
#> [51] -0.99838012

table(df$x < 0)
#> 
#> FALSE  TRUE 
#>    49    51

Created on 2018-06-22 by the reprex package (v0.2.0).


#3

FALSE TRUE
841679 786511

so true means 786511 data with negative values?


#4

@jcblum has the answer for what you want.

The answer for what happened: you used a parenthesis when you meant to use a bracket.

table(final_df$Gross_MarginDollars_Percentage( # here

final_df$Gross_MarginDollars_Percentage is (assumedly) a vector. Following it up with a parenthesis means it should be used as a function, but R notices it's not a function. Hence the error message

attempt to apply non-function

Errors and warnings can be cryptic, but they're also consistent. Now you'll know what this one means when it pops up again (and it will, for we are but humans who type with dumb fingers).


#5

Yup!

(Apparently that’s too short of a post, so here’s a pointless parenthetical :upside_down_face:)