1

I have a table data1 that looks like :

V1 V2 V3
A  B  1
A  C  1
A  D  0
A  E  1
A  F  0
A  G  0
A  H  0

and I would like to extract a subtable data2 and keep all line where V3 == 1 like:

V1 V2 V3
A  B  1
A  C  1
A  E  1

I did it by using a loop but it's not very elegant.

How to do this without a complex loop?

  • Assuming your data frame is `df` then `df[df$V3==1, ]` – dimitris_ps Apr 09 '15 at 14:02
  • 1
    This kind of subsetting is essential to learn if you want to do any analysis in R so you might want to also consult an introductory tutorial to R. – talat Apr 09 '15 at 14:06

2 Answers2

2

There are plenty of ways to do this in R. The most common ones are listed below.

# Selecting observations on conditions
data2 <- data1[V3 == 1, ]

# Excluding observations on conditions
data2 <- data1[!V3 != 1, ]

# Subset function
data2 <- subset(data1, V3 == 1)

#using packages:

# dplyr package
library(dplyr)
data2 <- filter(data1, V3 == 1)

# data.table package
library(data.table)
data2 <- setDT(data1)[V3 == 1]

Most R-users don't use the subset function for reasons mentioned in this post: Why is `[` better than `subset`?

Community
  • 1
  • 1
rmuc8
  • 2,869
  • 7
  • 27
  • 36
1

You can use subset function:

data2 <- subset (data1, V3 == 1)

Data

data <- data.frame(V1=c("A", "A", "A", "A", "A", "A", "A"),
                   V2=c("B", "C", "D", "E", "F", "G", "H"),
                   V3=c(1, 1, 0, 1, 0, 0, 0))
demonplus
  • 5,613
  • 12
  • 49
  • 68