【问题标题】:how subset a data frame by the column using a character string如何使用字符串按列对数据框进行子集化
【发布时间】:2015-04-21 10:55:51
【问题描述】:

我在 R 中有一个这样的数据框:

> df <- data.frame(cbind(C.01=1, C.02=1:8, C.03=c("A","B","C","D","E","F","G","H")))

我会得到一个像这样的子集:

> subset(df, C.03 == "A")

C.01 C.02 C.03
1    1    1    A

可以做相同的子集,但列的名称在xx &lt;- "C.03" ??

因为subset(df, xx == "A") 不起作用。

谢谢。

【问题讨论】:

标签: r dataframe subset


【解决方案1】:

使用基础 R(感谢@David Arenburg):

df[df[xx] == "A", ]

或者使用dplyr,我建议这样做是因为语法更容易理解:

require("dplyr")
df <- filter(df, C.03 == "A")

【讨论】:

    猜你喜欢
    • 2016-10-04
    • 2016-01-13
    • 2016-06-18
    • 2014-11-13
    • 1970-01-01
    • 1970-01-01
    • 2022-08-21
    • 1970-01-01
    • 2018-02-28
    相关资源
    最近更新 更多