【发布时间】:2019-09-18 16:41:33
【问题描述】:
下面数据框中的一列 (new) 是一个表格。
#dput(head(df1))
structure(list(a = c(1, 2, 3, 4, 5, 7), b = c(2, 3, 3, 5, 5,
7), c = c(1, 3, 2, 4, 5, 7), new = list(structure(2:1, .Dim = 2L, .Dimnames = structure(list(
c("1", "2")), .Names = ""), class = "table"), structure(1:2, .Dim = 2L, .Dimnames = structure(list(
c("2", "3")), .Names = ""), class = "table"), structure(1:2, .Dim = 2L, .Dimnames = structure(list(
c("2", "3")), .Names = ""), class = "table"), structure(2:1, .Dim = 2L, .Dimnames = structure(list(
c("4", "5")), .Names = ""), class = "table"), structure(c(`5` = 3L), .Dim = 1L, .Dimnames = structure(list(
"5"), .Names = ""), class = "table"), structure(c(`7` = 3L), .Dim = 1L, .Dimnames = structure(list(
"7"), .Names = ""), class = "table"))), row.names = c(NA,
6L), class = "data.frame")
new 列是apply(df1, 1, table) 的结果。
使用df1[4, "new"][[1]] 的new 列子集示例
产生以下输出。
df1[4, "new"][[1]]
#4 5 --> Vals
#2 1 --> Freq
我想制定一个条件,例如给我所有Vals,其中new 列中的Freq 大于或等于某个条件,并使用它来子集new 列。
这是一个例子,以及我到目前为止所做的事情。
df1[4, "new"][[1]][]>=2
# 4 5
# TRUE FALSE
# Subsetting using the above logical
as.integer(names(df1[4, "new"][[1]][df1[4, "new"][[1]][]>=2]))
#[1] 4
结果如我所愿。但是,它很冗长,如果有更短的版本,我会很高兴(目前这不是一个紧迫的问题,尽管我会很感激并很高兴学会写清晰简洁的线条)。
我遇到的紧迫问题是如何修改条件as.integer(names(df1[4, "new"][[1]][df1[4, "new"][[1]][]>=2])) 并将其应用于整个列。例如,对于条件列,新的== 3、5 和7 是预期的输出。
我看过here 和here 的类似帖子,但没有帮助弄清楚如何将子集条件应用于作为表格的列。
谢谢。
【问题讨论】:
-
您能具体说明您想要返回的内容吗?如果条件>3,您希望返回最后两行吗?还是只包含 5 和 7 的向量?如果条件 >=2 怎么办?你会返回所有的行吗?
-
谢谢。我想要的输出只是
5和7;当条件为>=2时,将是满足条件的new列中的特定值(names)。