Search code examples
rfrequency-analysis

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


Solution

  • 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"