# simple data subsetting on r

I have a big df like following (pseudo) df and I want to retrieve values in different col. according to the rows in the first col.

A B C D
a 1 1 1
a 2 3 1
a 3 3 3
a 4 5 6
b 5 6 5
b 7 6 5
c 7 6 5
c 5 4 3
c 5 5 4


I want to retrieve the values in col. B, C, and D according to the rows in col A and perform further analysis of them. For example, multiply the values in col B and C for all the rows of "a" in col A. Can someone suggest a commend for such a naive question. Thanks.

• I'm downvoting this because it doesn't have anything to do with bioinformatics, but you can use df[df$A=='a',], or dplyr::group_by(A) if you want to repeat the same analysis for each value of A Mar 12 '18 at 22:50 • That is not true, the original df contains genetic info. Thanks Mar 12 '18 at 23:06 • I'm voting to close this question as off-topic because without more context, this looks like a programming question better suited for Stack Overflow, and the "this question belongs on another site in the SE network" radio button does not offer Stack Overflow as a selection. Mar 13 '18 at 18:58 ## 1 Answer Here's an approach that uses native R, using the vectorized (fast) family of apply() functions. > df2 <- df[df$A == 'a', which(names(df) %in% c("B","C"))]
> apply(df2, 1, prod)


Use apply/lapply/mapply/etc. where you can in place of alternatives, where you don't know their run characteristics.

Here's a more concrete example:

> df
A B C D
1 a 1 1 1
2 a 2 3 1
3 a 3 3 3
4 a 4 5 6
5 b 5 6 5
...
> df2 <- df[df$A == 'a', which(names(df) %in% c("B","C"))] > df2 B C 1 1 1 2 2 3 3 3 3 4 4 5 > apply(df2, 1, prod) 1 2 3 4 1 6 9 20  Edit: If you need to do this on each unique value of df$A, you can nest apply calls to make this scale:

> perA.list <- apply(data.frame(unique(df$A)), 1, function(x) apply(df[df$A == x, which(names(df) %in% c("B","C"))], 1, prod))
> perA.list
[[1]]
1  2  3  4
1  6  9 20

[[2]]
5  6
30 35

[[3]]
7  8  9
35 20 25


Each index in this list correspondents to the index of the value from unique(df$A), i.e. a, b, and c. If you don't want to do this for all unique values in df$A, but for some specific element in df\$A, then you would just need to write a function. 95% of the code is in this answer to write such a function, so I'll leave that as a homework exercise for you to implement.

• Thanks, I can't able to mention "a"every time. First I also want to have same results for "b" and "c" as for "a". Second, as I mentioned the data is big with 70,000 entries. In this case please suggest something. Mar 12 '18 at 23:05
• See edited answer. Mar 12 '18 at 23:35
• Hi, ddply (rdocumentation.org/packages/plyr/versions/1.8.4/topics/ddply) was used to obtain results, exactly what I was looking. Thanks Mar 13 '18 at 17:26