user3354212 user3354212 - 1 year ago 84
R Question

Extract from a data frame column based on a list of indices

I have a data frame:

df = read.table(text="ID location C1 C2 C3 C4 C5 C6
M01 1 A H H A A B
M02 2 A H A A A B
M03 3 A B A A A B
M04 4 H B H A A B
M05 5 H B H A A B
M06 6 A B H A A H
M07 7 A B H B A H
M08 8 A B H A A H
M09 9 A B H A A H
M10 10 B B H A A H
M11 11 A B H A A H
M12 12 A B H A A H
M13 13 A B H A A H
M14 14 B B B A A H
M15 15 B B B A A A", header=T, stringsAsFactors=F)

I would like to extract out the values of
based on a list of index row numbers of
. The list

a = list(C1 = c(3, 5, 9, 10, 13), C2 = c(2) ,
C3 = c(1, 3, 13 ), C4 =c(6, 7 ), C6 = c(5, 14 ))

The expected result is:

[1] "M03" "M05" "M09" "M10" "M13"

[1] "M02"

[1] "M01" "M03" "M13"

[1] "M06" "M07"

[1] "M05" "M14"

Answer Source

You could unlist the a list, index the data values, then relist it with itself as the skeleton.

relist(df$ID[unlist(a)], a)
# $C1
# [1] "M03" "M05" "M09" "M10" "M13"
# $C2
# [1] "M02"
# $C3
# [1] "M01" "M03" "M13"
# $C4
# [1] "M06" "M07"
# $C6
# [1] "M05" "M14"

Additionally, we could get an increase in speed if we drop the names in unlist.

relist(df$ID[unlist(a, use.names = FALSE)], a)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download