比较来自世界各地的卖家的域名和 IT 服务价格
r

删除数据帧中的变量的第一个条目的行

我有一个具有两个变量,日期和分类的数据帧,我想得到每个分类群的第一个外观的日期。 在数据帧中包含 172 行,是 9 不同的日期我。 40 各种分类群,但我的答案应该只包含 40 学期。

分类群是一个因素,日期是日期。

例如,我的数据框架 /叫 'species'/ 配置如下:


Date Taxa
2013-07-12 A
2011-08-31 B
2012-09-06 C
2012-05-17 A
2013-07-12 C
2012-09-07 B


我会寻求这个答案:


Date Taxa
2012-05-17 A
2011-08-31 B
2012-09-06 C


我试图用:


t.first <- species[unique/species$Taxa/,]


它给了我正确的行数,但有重复的分类赛。 如果我只是用 unique/species$Taxa/, 它似乎给了我正确的答案,但是当我第一次发生时,我不知道日期。

谢谢你的帮助。
已邀请:

奔跑吧少年

赞同来自:

t.first <- species[match/unique/species$Taxa/, species$Taxa/,]



match

返回第一次巧合的索引,比较的载体中给出所需的线条。

快网

赞同来自:

在下一个团队中
duplicated

为重复值创建逻辑索引
data$Taxa

. 使用以下内容创建数据帧的子集:


data[!duplicated/data$Taxa/, ]


结果:


Date Taxa
1 2012-05-17 A
2 2011-08-31 B
3 2012-09-06 C

石油百科

赞同来自:

这是参数
dplyr

, 哪些不依赖于日期的日期顺序排序数据,并考虑到链接:


library/dplyr/
df %>%
mutate/Date = as.Date/Date// %>%
group_by/Taxa/ %>%
filter/Date == min/Date// %>%
slice/1/ %>% # takes the first occurrence if there is a tie
ungroup//

# A tibble: 3 x 2
Date Taxa
<date> <chr>
1 2012-05-17 A
2 2011-08-31 B
3 2012-09-06 C

# sample data:
df &lt;- read.table/text = 'Date Taxa
2013-07-12 A
2011-08-31 B
2012-09-06 C
2012-05-17 A
2013-07-12 C
2012-09-07 B', header = TRUE, stringsAsFactors = FALSE/


您可以得到相同的,按日期排序:


df %&gt;% 
mutate/Date = as.Date/Date// %&gt;%
group_by/Taxa/ %&gt;%
arrange/Date/ %&gt;%
slice/1/ %&gt;%
ungroup//


</chr></date>

帅驴

赞同来自:

这应该是一个技巧:


# Create some dummy data:

# Create some dates
Date=as.POSIXct/c/"2013-07-12","2011-08-31","2012-09-06","2009-01-01",
"2012-05-17","2013-07-12","2012-09-07","2013-02-02"//

# Create unique taxa
Taxa=rep/c/"A","B","C","D"/,2/

# Combine the two into a dataframe
data=as.data.frame/list/Date=Date,Taxa=Taxa//

# this returns a numeric vector of the minimum dates
xx=tapply/data$Date,list/data$Taxa/,min/

# And this will return a dataframe with the first occurence
# of your taxa /or variables/
as.data.frame/list/Date=as.POSIXct/xx,origin="1970-01-01"/,
Taxa=names/xx///


注意:您可以添加 simplify=T 在 tapply, 返回
一个东西 POSIXt, 但它返回一个列表。 更多详情可在这找到:
http://r.789695.n4.nabble.com/ ... .html

莫问

赞同来自:

这是一个解决方案
data.table

:


library/data.table/
setDT/species/
species[, .SD[which.min/Date/], by = Taxa]
# Taxa Date
# 1: A 2012-05-17
# 2: B 2011-08-31
# 3: C 2012-09-06


数据

:


species <- data.frame/
Date = as.Date/c/"2013-07-12", "2011-08-31", "2012-09-06",
"2012-05-17", "2013-07-12", "2012-09-07"//,
Taxa = c/"A", "B", "C", "A", "C", "B"/
/

要回复问题请先登录注册