【发布时间】: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 %>% group_by(type) %>% mutate(y = somefunction) 的东西。
但后来我被困在功能实现上。
我知道也可以使用ave 函数来完成,但最终会遇到同样的问题。
我会知道如何使用循环来实现,但我确信 R 有更好的方法。
【问题讨论】:
-
“类型 1 的所有值”是什么意思? X 值?行?
-
这个:
my.df[type == 'type1' & my.df$x < threshold.df$threshold[threshold.df$type == 'type1'], ]或my.df$x[type == 'type1' & my.df$x < threshold.df$threshold[threshold.df$type == 'type1']]给你想要的吗? -
x
-
您的解决方案适用于 type1,但我需要重复 type2。如果我有很多类型,我希望我可以自动化它。
-
你的问题是说你只想为 x 为 'type 1' 做它......
标签: r