user466663
user466663

Reputation: 845

subsetting a dataframe into a vector based upon a row value of another column in R

I have a dataframe, named ann, which has several hundred rows. I have shown only a few.

        Exp     Result
1   gmp_123     kip
2   gmp_345     kip
3   gmp_786     kip
4   gmp_564     min
5   gmp_347     min

Essentially I want to create two vectors from the column Exp. One will have Exp values where Result == "kip" and the other with Exp values where Result == "min".

So the first vector will have values of gmp_123, gmp_345, gmp_786 and the second will have the values of gmp_564, gmp_347.

I tried the subset method as follows:

ann.kiu <- subset(ann, select=Exp, subset(Result=="kip"))

But I am getting

"Error in subset.default(Result=="kip") : argument "subset" is missing, with no default" error

Thanks

Upvotes: 0

Views: 5925

Answers (3)

user2759975
user2759975

Reputation: 71

kip <- subset(ann, Result == 'kip')[,"Exp"]
min <- subset(ann, Result == 'min')[,"Exp"]

Try the above. This basically indexes the column of interest from the subset of either kip or min.

Upvotes: 0

Alexander Hanysz
Alexander Hanysz

Reputation: 801

It's a simple typo: you just need to add an equals sign:

ann.kiu<-subset(ann, select=Exp, subset=(Result=="kip"))

Edited to add: this is pasted straight out of my R session:

> Exp=c("gmp_123","gmp_345","gmp_786","gmp_564","gmp_374")
> Result=c(rep("kip",3),rep("min",2))
> ann=data.frame(Exp,Result)
> ann
      Exp Result
1 gmp_123    kip
2 gmp_345    kip
3 gmp_786    kip
4 gmp_564    min
5 gmp_374    min
> ann.kiu<-subset(ann, select=Exp, subset=(Result=="kip"))
> ann.kiu
      Exp
1 gmp_123
2 gmp_345
3 gmp_786

Is this what you wanted?

Upvotes: 1

Hong Ooi
Hong Ooi

Reputation: 57686

To create 2 vectors:

kip <- subset(ann, subset=(Result == "kip"), select=Exp, drop=TRUE)
min <- subset(ann, subset=(Result == "min"), select=Exp, drop=TRUE)

But it sounds like you really want to create 2 subsets of your data frame, in which case just omit the drop=TRUE part in the above.

Upvotes: 2

Related Questions