我有两个数据框。
daf <- data.frame (A = 1:10, J = 1:10, E = 11:20, D = 21:30, C= 41:50, B = 61:70, L = 3:12)
df2 <- data.frame (nam = c("A", "B", "C", "E", "D"), sn = 1:5)
> df2
nam sn
1 A 1
2 B 2
3 C 3
4 E 4
5 D 5
> daf
A J E D C B L
1 1 1 11 21 41 61 3
2 2 2 12 22 42 62 4
3 3 3 13 23 43 63 5
4 4 4 14 24 44 64 6
5 5 5 15 25 45 65 7
6 6 6 16 26 46 66 8
7 7 7 17 27 47 67 9
8 8 8 18 28 48 68 10
9 9 9 19 29 49 69 11
10 10 10 20 30 50 70 12
我想只拾取df2的nam中列出的变量名。我想保留df2的顺序。
daf.n <- colnames(daf)
df2.n <- df2[,1]
daf[df2.n%in%colnames(daf),]
A J E D C B L
1 1 1 11 21 41 61 3
2 2 2 12 22 42 62 4
3 3 3 13 23 43 63 5
4 4 4 14 24 44 64 6
5 5 5 15 25 45 65 7
6 6 6 16 26 46 66 8
7 7 7 17 27 47 67 9
8 8 8 18 28 48 68 10
9 9 9 19 29 49 69 11
10 10 10 20 30 50 70 12
上面是第一份工作,但是没有按照df2列nam的顺序排列列。有什么想法吗?
答案 0 :(得分:2)
不需要%in%
:
daf <- data.frame (A = 1:10, J = 1:10, E = 11:20, D = 21:30, C= 41:50, B = 61:70, L = 3:12)
df2 <- data.frame (nam = c("A", "B", "C", "E", "D"), sn = 1:5)
daf[,as.character(df2$nam)]
请注意,此处的示例data.frames略有改动。