【问题标题】:Replace data frame values by group using data from another data frame使用来自另一个数据帧的数据按组替换数据帧值
【发布时间】:2017-05-17 13:32:04
【问题描述】:

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

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 %&gt;% group_by(type) %&gt;% mutate(y = somefunction) 的东西。

但后来我被困在功能实现上。

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

我会知道如何使用循环来实现,但我确信 R 有更好的方法。

【问题讨论】:

  • “类型 1 的所有值”是什么意思? X 值?行?
  • 这个:my.df[type == 'type1' &amp; my.df$x &lt; threshold.df$threshold[threshold.df$type == 'type1'], ]my.df$x[type == 'type1' &amp; my.df$x &lt; threshold.df$threshold[threshold.df$type == 'type1']] 给你想要的吗?
  • x
  • 您的解决方案适用于 type1,但我需要重复 type2。如果我有很多类型,我希望我可以自动化它。
  • 你的问题是说你只想为 x 为 'type 1' 做它......

标签: r


【解决方案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

如果您希望阈值检查适用于所有类型而不仅仅是 type1,您可以这样做:

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

【讨论】:

    【解决方案2】:

    我只想合并数据。

    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]
    

    【讨论】:

    • 或者通过链my.df[threshold.df, on = .(type)][y &lt; threshold, y := 0][, threshold := NULL]
    猜你喜欢
    • 1970-01-01
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多