如何从R data.frame获取行 [英] How to get row from R data.frame

查看:786
本文介绍了如何从R data.frame获取行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有列标题的数据框架。



如何从数据框架中获取特定行作为列表(列标题作为列表的键)?



具体来说,我的数据框架是

 
ABC
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)
abc
5.0 4.25 4.5


解决方案

  x [r,] 

其中r是您感兴趣的行,请尝试这样,例如:

  #Add你的数据
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)


#矢量你的结果应该匹配
y< -c(A = 5,B = 4.25,C = 4.5)

#测试行中的项目与您想要的向量匹配
x [1,] == y

本页(从这个有用的网站)有很好的索引信息,像这样。


I have a data.frame with column headers.

How can I get a specific row from the data.frame as a list (with the column headers as keys for the list)?

Specifically, my data.frame is

      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

And I want to get a row that's the equivalent of

> c(a=5, b=4.25, c=4.5)
  a   b   c 
5.0 4.25 4.5 

解决方案

x[r,]

where r is the row you're interested in. Try this, for example:

#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 (from this useful site) has good information on indexing like this.

这篇关于如何从R data.frame获取行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆