Ani
Ani

Reputation: 61

R- Count of Specific values and Print in R

I have created data frame "df"

Age Sex Income
45  Female  3000
25  Female  5000
34  Male    4500

Now I want to count no of females in sex column and Print it like " No of Females = 2" without using any special package

I could see number of male and female while giving code: summary(df$Sex)or table(df$sex)

Tried doing Femdata=df[which(df$Sex =='Female'),] not working sum(df$sex=="Female", na.rm=TRUE) not working df$sex[df$sex=="Female"] not working length(df[df$sex=="Female"]) not working Kindly let me know the solution And also Kindly help me in Printing with some statement and then answer

Upvotes: 3

Views: 5851

Answers (3)

Rudy
Rudy

Reputation: 387

try

nrow(df[df[,2]=="Female",])

The issue here is you missed a comma (,) in matrix dataframe, so it returns error. Also the column names are case sensitive, it must be an exact match!

Upvotes: 0

smci
smci

Reputation: 33970

Even simpler, to get the count:

sum(df$Sex == 'Female')

and to print it, your options are as Ananda Mahto said.

Upvotes: 1

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193677

Generally, you can use cat to print extra information with an answer:

> cat("No of Females = ", nrow(mydf[mydf$Sex == "Female", ]))
No of Females =  2

If you want the result as a character string to use elsewhere, it's probably easier to use sprintf or paste:

> sprintf("No of Females = %s", nrow(mydf[mydf$Sex == "Female", ]))
[1] "No of Females = 2"

Upvotes: 3

Related Questions