R:删除组内的所有观察结果

问题描述 投票:0回答:1

我有一组500家公司,其中有六年的投资数据。我只希望创建具有所有六个年的数据对企业的平衡板,但我似乎无法找到一个简单的方法R中做到这一点。

我的数据如下:

IMAGE

如果一家公司仅缺少一年的价值,我想将其全部丢掉。我尝试了不同的条件子集命令,但没有任何工作对我有用。想法?

r conditional-statements subset
1个回答
0
投票

三种方法:

dat <- data.frame(
  firm = c(1, 1, 1, 2,  2,  2),
  year = c(1, 2, 3, 1,  2,  3),
  val  = c(1, 1, 1, 2, NA, NA)
)

Base R

do.call(
  rbind.data.frame,
  by(dat, dat$firm, function(x) if (!any(is.na(x$val))) x)
)
#     year firm val
# 1.1    1    1   1
# 1.2    2    1   1
# 1.3    3    1   1

data.table

library(data.table)
datDT <- as.data.table(dat)
datDT[, .SD[!any(is.na(val)),], by = "firm" ]

dplyr

library(dplyr)
dat %>%
  group_by(firm) %>%
  filter(!any(is.na(val))) %>%
  ungroup()
© www.soinside.com 2019 - 2024. All rights reserved.