Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

In R, how can I count instances of a dummy variable =1?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...