Vatsal
Vatsal

Reputation: 13

Unexpected error '=' while subsetting observations in r

I am trying to subset specific observations in a dataset.

I have four columns: Trial_code, Flanker, RT and correct

Here is snippet from my dataframe:

Trial_code Flanker   RT correct
1    validspatialcue1       1  621       1
2           doublecue       2  730       1
3               nocue       1  796       1
4   invalidspatialcue       1  511       1
5    validspatialcue3       2  736       1
6               nocue       1  593       1
7    validspatialcue2       2  682       1
8           doublecue       2  690       1
9   invalidspatialcue       1  641       1
10   validspatialcue1       1  476       1
11   validspatialcue3       2  573       1

I am trying to select and create a dataframe of observations that meet the following criteria

The entry in Trial_code should either of these:

validspatialcue1, validspatialcue2, validspatialcue3

and

Values in Flanker should be equal to 1

In order to accomplish this I wrote the following code:

data1 <- subset(mydata, Trial_code=="validspatialcue1",Trial_code=="validspatialcue2",Trial_code=="validspatialcue3" & Flanker=1)

I am getting the following error:

Error: unexpected '=' in "data1 <- subset(mydata, Trial_code=="validspatialcue1",Trial_code=="validspatialcue2",Trial_code=="validspatialcue3" & Flanker="

Can anyone please help on this because I am not sure what mistake I am doing here.

Upvotes: 0

Views: 63

Answers (2)

MHammer
MHammer

Reputation: 1314

Your last statement is using =, and needs to be == instead

data1 <- subset(mydata, Trial_code=="validspatialcue1",Trial_code=="validspatialcue2",Trial_code=="validspatialcue3" & Flanker==1)

Upvotes: 0

Nicol&#225;s Velasquez
Nicol&#225;s Velasquez

Reputation: 5898

Try this:

mydata[grepl('^validspatialcue[123]', mydata$Trial_code) & 
       mydata$Flanker == 1, ]

Here you provide two arguments. The first one -grepl(...)- looks in the varaible Trial_code for the following string:

  1. That starts the line ("^") with the string "validspatialcue". The start of the line "^" is important to preclude false positives with "invalidspatialcue".
  2. Is followed by either 1, 2 or 3 ("[123]").

The second one looks for cases where mydata equals 1.

The "&" signs instructs the sub-setting to look for the previous conditions to be simultaneously true.

Do not forget the comma "," before closing the braquets!

Upvotes: 1

Related Questions