1
votes

I have dataset (b.data) containing information on marine species recorded in a survey. Each row relates to an individual animal with the column headings below:

"Area" "Year" "Cruise" "Vessel" "Haul" "Haul_ID" "Common_name" "Scientific_Name" "Length_mm" "Sex" "Width"

I want to subset the data to only include certain species for analysis. I have written the code below naming the species I want to include (31 species)

species.list <- c("Blonde ray","Brown crab","Cod","Common dab", ... etc

I don't know how to write the code to then subset these rows from the whole dataset. I have tried the code below but it returns 0 observations.

z=b.data[rownames(b.data$Common_name) %in% species.list,]
2
Try z <- b.data[ b.data$Common_name %in% species.list, ] - zx8754

2 Answers

2
votes

Nearly there I think - how about

z=b.data[b.data$Common_name %in% species.list,]
1
votes

You just need to get rid of the row.names(). Consider:

b.data <- data.frame(Common_name=c("Blonde ray","Brown crab","Cod",
                                   "Common dab", LETTERS[1:7]), 
                     x=rnorm(11))
b.data
#    Common_name          x
# 1   Blonde ray  0.3631655
# 2   Brown crab -0.6668250
# 3          Cod -0.2829071
# 4   Common dab  0.3893549
# 5            A  0.7206768
# 6            B -0.9790288
# 7            C -0.5366370
# 8            D  1.9940040
# 9            E  1.2800009
# 10           F -0.2024495
# 11           G -2.1230087

Here is what row.names() returns:

row.names(b.data)
# [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10" "11"
row.names(b.data$Common_name)
#

For the b.data it is the row numbers, since I didn't assign any row names, and b.data$Common_name is just a variable in the data frame, it doesn't have any row names at all. Here is what you get if you leave row.names() out:

species.list <- c("Blonde ray","Brown crab","Cod","Common dab")
z = b.data[b.data$Common_name %in% species.list,]
z
#   Common_name          x
# 1  Blonde ray  0.3631655
# 2  Brown crab -0.6668250
# 3         Cod -0.2829071
# 4  Common dab  0.3893549