我有一个带有列标题的data.frame。如何从R数据框中获得行
如何从data.frame中获取特定行作为列表(将列标题作为列表的键)?
具体来说,我data.frame是
A B C 1 5 4.25 4.5 2 3.5 4 2.5 3 3.25 4 4 4 4.25 4.5 2.25 5 1.5 4.5 3
而且我希望得到一个排那的
> c(a=5, b=4.25, c=4.5)
a b c
5.0 4.25 4.5
我有一个带有列标题的data.frame。如何从R数据框中获得行
如何从data.frame中获取特定行作为列表(将列标题作为列表的键)?
具体来说,我data.frame是
A B C 1 5 4.25 4.5 2 3.5 4 2.5 3 3.25 4 4 4 4.25 4.5 2.25 5 1.5 4.5 3
而且我希望得到一个排那的
> c(a=5, b=4.25, c=4.5)
a b c
5.0 4.25 4.5
x[r,]
其中r是你感兴趣的行。试试这个,例如:
#Add your data
x <- structure(list(A = c(5, 3.5, 3.25, 4.25, 1.5),
B = c(4.25, 4, 4, 4.5, 4.5),
C = c(4.5, 2.5, 4, 2.25, 3 )
),
.Names = c("A", "B", "C"),
class = "data.frame",
row.names = c(NA, -5L)
)
#The vector your result should match
y<-c(A=5, B=4.25, C=4.5)
#Test that the items in the row match the vector you wanted
x[1,]==y
This page(从this useful site)对这样的索引良好的信息。
尝试等价的:
> d <- data.frame(a=1:3, b=4:6, c=7:9)
> d
a b c
1 1 4 7
2 2 5 8
3 3 6 9
> d[1, ]
a b c
1 1 4 7
> d[1, ]['a']
a
1 1
如果你不知道的行数,但确实知道一些值,则可以使用子集
x <- structure(list(A = c(5, 3.5, 3.25, 4.25, 1.5),
B = c(4.25, 4, 4, 4.5, 4.5),
C = c(4.5, 2.5, 4, 2.25, 3 )
),
.Names = c("A", "B", "C"),
class = "data.frame",
row.names = c(NA, -5L)
)
subset(x, A ==5 & B==4.25 & C==4.5)
逻辑索引是很R-ISH。尝试:
x[ x$A ==5 & x$B==4.25 & x$C==4.5 , ]
或者:
subset(x, A ==5 & B==4.25 & C==4.5)
你的意思是这样呢? subset(x,A == 5 && B == 4.25 && C == 4.5) – momeara 2010-07-08 20:23:54
不,它应该是:'subset(x,A == 5&B == 4.25&C == 4.5)' – 2013-08-20 00:24:54