【问题标题】:R: error when trying a loop with dplyr filter functionR:尝试使用 dplyr 过滤器功能循环时出错
【发布时间】:2019-01-02 04:47:47
【问题描述】:

为了简化和使我的代码可重现,我有以下循环代码,旨在对数据框进行子集化并将每个子集存储在一个新变量中:

types <- c("POINT", "NONPOINT", "ON-ROAD", "NON-ROAD")

for (i in seq_along(types)) {
   paste("type", types[i], sep = "") <- filter(NEI$Emissions, NEI$type == types[i])
}

我希望我的循环将每个子集(4 个子集)存储在一个名为“type”的新变量和相应的字符串中。而不是它,我收到以下错误:

"UseMethod("filter_") 中的错误: 没有适用于“filter_”的方法应用于“c('double', 'numeric')”类的对象

我已经尝试修改通过as.character(types) 将其强制为字符串的类型类,但没有成功。

编辑:head(NEI) 的输出如下:

   fips      SCC  Pollutant Emissions  type year
4  09001 10100401  PM25-PRI    15.714 POINT 1999
8  09001 10100404  PM25-PRI   234.178 POINT 1999
12 09001 10100501  PM25-PRI     0.128 POINT 1999
16 09001 10200401  PM25-PRI     2.036 POINT 1999
20 09001 10200504  PM25-PRI     0.388 POINT 1999
24 09001 10200602  PM25-PRI     1.490 POINT 1999

【问题讨论】:

  • 大多数情况下你应该通过split(NEI$Emissions, NEI$type)得到你想要的东西
  • 您能否添加来自dput(head(data)) 的输出,以便我们更轻松地提供帮助?
  • 刚刚完成,检查我的编辑。 @RAB
  • 我猜你想要实现的目标需要assign
  • @Mauro 然后做split(NEI, NEI$type)

标签: r for-loop subset


【解决方案1】:

你想做的是

types <- c("POINT", "NONPOINT", "ON-ROAD", "NON-ROAD")

for (i in types) {
  assign(paste0("type", i), filter(NEI, NEI$type == i))
}

这将为您提供 4 个基于 types 的数据帧

mtcars 数据集上试试这个

cyl <- unique(mtcars$cyl)

for (i in cyl) {
  assign(paste0("type", i), filter(mtcars, mtcars$cyl == i))
}

type6
#   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#1 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
#2 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
#3 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
#4 18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
#5 19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
#6 17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
#7 19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6

以及类似的其他数据帧。

您的解决方案不起作用的原因是因为您试图将值分配给可以通过执行复制的字符

paste0("type", types[1]) <- filter(mtcars$mpg, mtcars$cyl == 4)

UseMethod("filter_") 中的错误: 没有适用于“c('double', 'numeric')”类对象的“filter_”方法

但是,using assign is bad,如 cmets 中所述,您可以使用 split,它会为您提供数据帧列表。

new_data <- split(NEI, NEI$type)

然后通过new_data[[1]]new_data[[2]] 等方式访问它们。

【讨论】:

    猜你喜欢
    • 2019-07-28
    • 2014-12-31
    • 1970-01-01
    • 2021-10-22
    • 2014-02-03
    • 2023-03-21
    • 1970-01-01
    • 2021-07-06
    相关资源
    最近更新 更多