使用来自另一个数据帧的数据按组替换数据帧值

时间:2017-05-17 13:32:05

标签: r

我有一个包含不同数据类型阈值的数据框:

threshold <- c(5, 10)
type <- c("type1", "type2")
threshold.df <- data.frame(type, threshold)

这给出了:

> threshold.df
   type threshold
1 type1         5
2 type2        10

在另一个数据框中,我有:

x <- rep(1:30, 2)
y <- x^2
type <- rep(c("type1", "type2"), each = 30)
my.df <- data.frame(x, y, type)

给出了:

> head(my.df)
  x  y  type
1 1  1 type1
2 2  4 type1
3 3  9 type1
4 4 16 type1
5 5 25 type1
6 6 36 type1

现在,我想替换类型1的所有y值,其中x低于阈值0。

使用dplyr,我在考虑类似my.df %>% group_by(type) %>% mutate(y = somefunction)的内容。

但是我仍然坚持功能实现。

我知道也可以使用ave函数完成,但最终会出现同样的问题。

我知道如何使用循环来完成它,但我确信R有更好的方法。

2 个答案:

答案 0 :(得分:1)

我只是合并数据。

require(data.table)
setDT(threshold.df)
setDT(my.df)
my.df <- merge(my.df, threshold.df, by = 'type')
my.df[y < threshold, y := 0]
my.df[, threshold := NULL]

答案 1 :(得分:1)

以下是使用dplyr执行此操作的一种方法:

my.df %>%
  inner_join(., threshold.df) %>%
  mutate(y = ifelse(x < threshold & type == 'type1', 0, y)) %>%
  select(-threshold)

结果是这样的:

    x   y  type
1   1   0 type1
2   2   0 type1
3   3   0 type1
4   4   0 type1
5   5  25 type1
6   6  36 type1
7   7  49 type1
8   8  64 type1
9   9  81 type1
10 10 100 type1
11 11 121 type1
12 12 144 type1

如果您希望阈值检查适用于所有类型而不仅仅是类型1,您可以执行以下操作:

my.df %>%
  inner_join(., threshold.df) %>%
  mutate(y = ifelse(x < threshold, 0, y)) %>%
  select(-threshold)