Reputation: 1821
If I have a data frame with categorical rows describing the columns, how can I subset it based on those values? Here is my data:
name1 name2 name3
cond trt ctrl ctrl
hour 0 3 0
A 1 1 1
B 2 2 2
C 3 3 3
D 4 4 4
E 5 5 5
F 6 1 6
G 7 2 7
H 8 3 8
I 9 4 9
J 10 5 10
Recreate it with this line:
A <- structure(list(name1 = c("trt", "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "10"), name2 = c("ctrl", "3", "1", "2", "3",
"4", "5", "1", "2", "3", "4", "5"), name3 = c("ctrl", "0", "1",
"2", "3", "4", "5", "6", "7", "8", "9", "10")), .Names = c("name1",
"name2", "name3"), row.names = c("cond", "hour", "A", "B", "C",
"D", "E", "F", "G", "H", "I", "J"), class = "data.frame")
Here is what I've attempted:
subset(A, ( A[1,] == 'trt' & A[2,] == 0 ))
My unexplainable result. Why this?:
name1 name2 name3
cond trt ctrl ctrl
B 2 2 2
E 5 5 5
H 8 3 8
What I want:
name1
cond trt
hour 0
A 1
B 2
C 3
D 4
E 5
F 6
G 7
H 8
I 9
J 10
Thank you. This might be easier if the categories of 'cond' and 'hour' were factors. Or if the data was 'melted'. I'm open to any suggestions.
Upvotes: 1
Views: 1321
Reputation: 17189
Alongwith direct subsetting with [ ]
, you can also use subset
's select arguement to select columns
> subset(A, TRUE, select=( A[1,] == 'ctrl' & A[2,] == 3 ))
name2
cond ctrl
hour 3
A 1
B 2
C 3
D 4
E 5
F 1
G 2
H 3
I 4
J 5
Upvotes: 1
Reputation: 59970
Don't need to use subset. Just do:
A <- A[,1,drop=FALSE]
Or if you don't want to hard-code the column number:
A[,A[1,] == 'trt' & A[2,] == 0,drop = FALSE]
Upvotes: 3