-1

I'm new to R studio, studying it for a maths module in year 2. I've been set a question "run a command to display all of the rows where the contestant is male". I've tried using the subset function and the $, but I cant seem to figure it out.

Age = c(25, 23, 33, 28, 35, 31, 25, 29)
Gender = c(Male, Male, Female, Female, Male, Female, Female, Female)
Cinema = c(T, T, T, T, F, F, T, F)
Shopping = c(F, F, F, T, T, T, F, F)
df = data.frame(Age, Gender, Cinema, Shopping) #data frame of dating show data

This is the date frame, can anyone point me in the right direction?

Sotos
  • 51,121
  • 6
  • 32
  • 66
F. Wotton
  • 45
  • 1
  • 6

1 Answers1

0

First of all, you need to put the Gender into quotes so it is recognized as a string and not a variable:

Age = c(25, 23, 33, 28, 35, 31, 25, 29)
Gender = c("Male", "Male", "Female", "Female", "Male", "Female", "Female", "Female")
Cinema = c(T, T, T, T, F, F, T, F)
Shopping = c(F, F, F, T, T, T, F, F)
df = data.frame(Age, Gender, Cinema, Shopping) #data frame of dating show data

to view all rows where Gender = Male you can use the following command

> df[df$Gender == 'Male',]

  Age Gender Cinema Shopping
1  25   Male   TRUE    FALSE
2  23   Male   TRUE    FALSE
5  35   Male  FALSE     TRUE
f.lechleitner
  • 3,554
  • 1
  • 17
  • 35
  • Thank you, can you explain why I needed to use quotes for the gender column? – F. Wotton Oct 16 '17 at 12:07
  • @F.Wotton you really need to read a book and get started with R. Here is a couple of books, [book 1](http://www.burns-stat.com/pages/Tutor/R_inferno.pdf), and [book 2](http://franknarf1.github.io/r-tutorial/_book/index.html#introduction) – Sotos Oct 16 '17 at 12:27
  • using `c(Male, Female, ...)` would combine the variables `Male` and `Female`. You want to combine the STRINGS "Male" and "Female", etc, so you need to declare them as such. Your code would work if Male and Female were some sort of variable, but that's not what you want. For example: `Male <- 2` and `Female <- 3` using `> c(Male, Male, Female, Female, Male, Female, Female, Female)` would lead to `[1] 2 2 3 3 2 3 3 3` - Information on strings in R: https://www.tutorialspoint.com/r/r_strings.htm - General tutorial: http://www.statmethods.net/r-tutorial/index.html – f.lechleitner Oct 16 '17 at 12:43