ljh2001
ljh2001

Reputation: 463

Subsetting a dataframe by partial Data point names

I have a dataframe of detections from acoustic receivers. I have about 70 receivers and am looking to subset my data by "line" of receivers. Station names are indicated as such: "TRC1-69", "TRC1-180", "TRC2-69", "TRC2-180".... "TRD1-69", "TRD1-180", "TRD2-69", "TRD2-180". Basically I'm trying to get all the C receivers in one dataframe, the D receivers in one dataframe and so on.

This is what I've tried so far

Dline <- AC[rownames(AC) %like% "TRD", ]

or

Dline <- subset(AC, Station == "TRD")

Upvotes: 1

Views: 65

Answers (3)

akrun
akrun

Reputation: 887711

We can use grepl in subset when there is partial match

subset(AC, grepl("^TRD", Station))

and to do this in one step, split into a list of data.frames

lst1 <- split(AC, grepl("^TRD", AC$Station))

Upvotes: 1

Sotos
Sotos

Reputation: 51582

You can use simple regex via gsub, i.e. (Using @Moody_Mudskipper data set)

split(df1, gsub('(.*)[0-9]+-[0-9]+', '\\1', rownames(df1)))
#$`TRC`
#         val
#TRC1-69    1
#TRC1-180   2
#TRC2-69    3
#TRC2-180   4

#$TRD
#         val
#TRD1-69    5
#TRD1-180   6
#TRD2-69    7
#TRD2-180   8

Upvotes: 1

moodymudskipper
moodymudskipper

Reputation: 47340

Here's a way:

df1 <- data.frame(
  val = 1:8,
  row.names =  c("TRC1-69", "TRC1-180", "TRC2-69", "TRC2-180", 
                 "TRD1-69", "TRD1-180", "TRD2-69", "TRD2-180"))

split(df1, substr(row.names(df1),3,3))

# $C
# val
# TRC1-69    1
# TRC1-180   2
# TRC2-69    3
# TRC2-180   4
# 
# $D
# val
# TRD1-69    5
# TRD1-180   6
# TRD2-69    7
# TRD2-180   8

Upvotes: 2

Related Questions