TheRealFakeNews
TheRealFakeNews

Reputation: 8143

R: How to obtain corresponding column of values?

Let's say I have three columns A, B, and C. I've taken a subset of A (say every other row), how do I obtain the corresponding values of those rows in C?

    A   B   C
1   a1  a1  c1
2   a2  b2  c2
3   a3  b3  c3
4   a4  b4  c4

I want:

     A   C
1   a1  c1
2   a3  c3

Note: using every other row for the subset in column A was just an example, I'm looking for a more general solution. That is, if I have a subset of the column A, how do I get the corresponding values in column C?

Upvotes: 2

Views: 51

Answers (1)

akrun
akrun

Reputation: 886948

We can recycle the TRUE/FALSE as the row index to get alternating rows, and column names as column index to subset the dataset.

df1[c(TRUE, FALSE),c('A', 'C')]
#   A  C
#1 a1 c1
#3 a3 c3

If we want to subset the rows based on the values in 'A', create the row index based on 'A' and select the columns that we need to have in the expected output.

df1[df1$A %in% c('a1', 'a3'), c('A', 'C')]

If we are using data.table (convert the data.frame to data.table using setDT) , we can set the key column and then directly subset the rows by using the elements in the 'subA'. For the column index, it is similar as above, but we need to use with=FALSE. More info can be found at ?data.table

library(data.table)
subA <- c('a1', 'a3')
setDT(df1, key='A')[subA, c('A', 'C'), with=FALSE]
#   A  C
#1: a1 c1
#2: a3 c3

Upvotes: 1

Related Questions