什么函数允许我根据R中列中的值从数据框中的列中提取数据?

问题描述 投票:0回答:2

我正在尝试根据列中的值从特定列中提取数据。

例如:

foo    bar
x      13
x      26             
y      52
x      43
y      76

x.values <- some.function(foobar = data.frame, key.value = key value to sort by)
y.values <- some.function(foobar = data.frame, key.value = key value to sort by)
x.values
>>> (13, 26, 43)
y.values
>>> (53, 76)
r sorting data-structures
2个回答
0
投票

假设您的数据帧被称为df:使用Base R代码:

x.values <- df[df$foo == "x",]$bar
y.values <- df[df$foo == "y",]$bar

这类似于SQL中的“Where”子句。对于foo ==“x”的行,我们查询数据框的列“foo”。如果我们在语句末尾添加“$ bar”,我们将获得相应行中bar列的值。但是,如果省略“$ bar”,查询将返回整行。


0
投票

假设您的数据框名为mydata

x.values <- mydata$bar[mydata$foo == "x"]
y.values <- mydata$bar[mydata$foo == "y"]
© www.soinside.com 2019 - 2024. All rights reserved.