Juliet R
Juliet R

Reputation: 223

Error trying to extract rows with a specific column value in r?

Having trouble. Here's an example of my dataframe (which has 4k rows). I want to extract rows that have a certain name in the LocationID column ("D").

D, AWC_Code
Yukon, 2
Unimak, 3
Taku River, 4
Banana, 5
Tailgate, 6

However I keep getting an error when I use this script. Thoughts?

awc3 <- awc2[ D == "Unimak" | D == "Taku River" ]

Error in D == "Unimak" : 
comparison (1) is possible only for atomic and list types

Upvotes: 1

Views: 169

Answers (3)

sairaamv
sairaamv

Reputation: 86

I believe, you got awc3 as a data.frame with two columns.

library(dplyr)  
awc3 <- filter(awc2, D %in% c("Unimak", "Taku River"))
# or, this should also do the trick 
awc2[awc2$D %in% c("Unimak", "Taku River"),]

Upvotes: 1

HubertL
HubertL

Reputation: 19544

In base R you can use dataframe$column to do logical indexing:

awc3 <- awc2[ awc2$D == "Unimak" | awc2$D == "Taku River", ]

Upvotes: 3

M--
M--

Reputation: 28825

You can use dplyr::filter

library(dplyr)
awc3 <- filter(awc2, D == "Unimak" | D == "Taku River" )

Upvotes: 5

Related Questions