R - number of specific values ​​and print in R

I have created a data frame "df"

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

      

Now I want to count the number of women in the sex column and print it as "No of Females = 2" without using a special bag

I could see the number of men and women by giving the code: summary(df$Sex)

ortable(df$sex)

Tried it Femdata=df[which(df$Sex =='Female'),]

doesn't work sum(df$sex=="Female", na.rm=TRUE)

doesn't work df$sex[df$sex=="Female"]

doesn't work length(df[df$sex=="Female"])

doesn't work Please let me know the solution. And also please help me to print with some expression and then answer

+3


source to share


3 answers


Typically, you can use cat

to print additional information with the answer:

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

      




If you want the result to be used as a character string elsewhere, it might be easier to use sprintf

either paste

:

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

      

+3


source


It's even easier to get the counter:

sum(df$Sex == 'Female')

      



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

+1


source


try

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

      

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

0


source







All Articles