If variable X is an integer;
mtcars$am
[1] 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1
> sum(mtcars$am)
[1] 13
If variable X is a factor (or character);
> sum(as.factor(mtcars$am) == "1")
[1] 13
You can check by using class()
;
> class(mtcars$am)
[1] "numeric"
> class(as.factor(mtcars$am))
[1] "factor"
mtcars is a build in dataset for R (you can use data()
) to see a list of built in datasets.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…