r - 使用 R 从数据框中子集表列
问题描述
下面数据框中的一列 ( 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)
。new
列子集使用 的示例df1[4, "new"][[1]]
产生以下输出。
df1[4, "new"][[1]]
#4 5 --> Vals
#2 1 --> Freq
我想制定一个条件,例如给我列中的所有Vals
位置大于或等于某个条件,并使用它来对列进行子集化。 Freq
new
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]))
并将其应用于整个列。例如,对于条件列 new == 3
,5
和7
是预期的输出。
我在这里和这里看到过类似的帖子,但没有帮助弄清楚如何将子集条件应用于作为表格的列。
谢谢你。
解决方案
调查class
对象(即列)产生"list"
。
class(df1$new)
# [1] "list"
通常我们使用例如lapply()
函数将函数应用于列表的元素。为了获得向量或矩阵而不是列表,我们可以尝试sapply
。
所以,定义你的条件,
COND <- 2
并在 a 中使用您的功能sapply
:
sapply(df1$new, function(x) as.numeric(names(x[x >= COND])))
# [1] 1 3 3 4 5 7
推荐阅读
- java - N条平行线的最小交叉
- api - 如何将数据从 Jenkins API 提取到 Google Sheet
- javascript - 如何在 mxgraph 中创建上下文填充?
- linux - 每当我重新启动 docker/elk 映像时,数据都会丢失
- linux - linux拆分数据并获得预期的输出
- python - 将多个图像转换为数组并找到平均值
- php - 我想通过调用php函数而不是文件在php中使用ajax上传图像
- java - Jolt 不要将 json 转换为另一个 json
- react-native - react-native 应用程序中的可访问性问题
- c# - 以编程方式设置按钮的前景文本颜色