[英]How to subset a unigue value in a column from data.table to new data.table
I have a data.table that I am wanting to subset and create another data.table based on the Counter variable.我有一个 data.table,我想根据 Counter 变量对其进行子集化并创建另一个 data.table。
The pseudo code would be create a new data.table of only unique Subject
from old data.table where Counter
is = 5伪代码将创建一个新的 data.table 仅来自旧 data.table 的唯一
Subject
,其中Counter
为 5
new_data <- old_data[Counter == 5, ]
but will this give me every time the counter reaches 5, I need it to only give it to me the first time但这会在每次计数器达到 5 时给我吗,我需要它只在第一次给我
Old data.table:
+---------------+------------+--------------+
| Date | Subject | Counter |
+---------------+------------+--------------+
| 10-21-20 | a | 0 |
+---------------+------------+--------------+
| 10-22-20 | a | 1 |
+---------------+------------+--------------+
| 10-23-20 | a | 2 |
+---------------+------------+--------------+
| 10-21-20 | b | 0 |
+---------------+------------+--------------+
| 10-26-20 | b | 5 |
+---------------+------------+--------------+
| 11-2-20 | b | 5 |
+---------------+------------+--------------+
| 11-7-20 | b | 5 |
+---------------+------------+--------------+
New data.table
+---------------+------------+--------------+
| 10-26-20 | b | 5 |
+---------------+------------+--------------+
We can wrap with unique
to get the first row by
the 'Subject'我们可以用
unique
换行by
获取“主题”的第一行
library(data.table)
unique(old_data[Counter == 5, ], by = c('Subject'))
Or another option is match
where match
returns the index of the first row that matches and use that to subset或者另一个选项是
match
,其中match
返回匹配的第一行的索引并将其用于子集
old_data[match(5, Counter)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.