简体   繁体   中英

Selecting specific rows in r based on condition

I have a table in r called "Tc" that contains various data as shown below:

Tc[1:5,]
                tFirst             tSecond type
1  2013-05-21 23:19:56 2013-05-22 13:33:12    2
2  2013-05-22 13:33:12 2013-05-22 14:29:44    1
3  2013-05-22 14:29:44 2013-05-22 17:02:18    2
4  2013-05-22 17:02:18 2013-05-22 17:13:29    1
5  2013-05-22 17:13:29 2013-05-22 19:42:14    2

I have another dataset in r called "Df" thta contains either a TRUE or FALSE for the same rows in Tc, as shown below:

Df
  [1] FALSE TRUE FALSE TRUE TRUE

How can I apply Df in creating a new table from Tc, let's call it newTc, where only the rows associated with a TRUE appear? So the expected output using my examples for newTc would be:

newTc
                tFirst             tSecond type
2  2013-05-22 13:33:12 2013-05-22 14:29:44    1
4  2013-05-22 17:02:18 2013-05-22 17:13:29    1
5  2013-05-22 17:13:29 2013-05-22 19:42:14    2

Tc and Df contain about 700 rows, these examples are just portions.

your code would be

newTc <- Tc[which(Df[1,] == TRUE),]    

.

To subset the rows of Tc for the TRUE values of the vector Df , you can simply do

Tc[Df,]

Here's how I'm presuming your data is set up, based on your examples:

> Tc <- read.table(h=T, text = "tFirst             tSecond type
  1  '2013-05-21 23:19:56' '2013-05-22 13:33:12'    2
  2  '2013-05-22 13:33:12' '2013-05-22 14:29:44'    1
  3  '2013-05-22 14:29:44' '2013-05-22 17:02:18'    2
  4  '2013-05-22 17:02:18' '2013-05-22 17:13:29'    1
  5  '2013-05-22 17:13:29' '2013-05-22 19:42:14'    2")
> Df <- c(FALSE, TRUE, FALSE, TRUE, TRUE)
> Tc[Df,]
#                tFirst             tSecond type
# 2 2013-05-22 13:33:12 2013-05-22 14:29:44    1
# 4 2013-05-22 17:02:18 2013-05-22 17:13:29    1
# 5 2013-05-22 17:13:29 2013-05-22 19:42:14    2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM