r - 根据相邻列的值替换多列中的值
问题描述
# Create a data frame
> df <- data.frame(a = rnorm(7), b = rnorm(7), c = rnorm(7), threshold = rnorm(7))
> df <- round(abs(df), 2)
>
> df
a b c threshold
1 1.17 0.27 1.26 0.19
2 1.41 1.57 1.23 0.97
3 0.16 0.11 0.35 1.34
4 0.03 0.04 0.10 1.50
5 0.23 1.10 2.68 0.45
6 0.99 1.36 0.17 0.30
7 0.28 0.68 1.22 0.56
>
>
# Replace values in columns a, b, and c with NA if > value in threshold
> df[1:3][df[1:3] > df[4]] <- "NA"
Error in Ops.data.frame(df[1:3], df[4]) :
‘>’ only defined for equally-sized data frames
可能有一些我无法产生的明显解决方案。目的是如果值大于“阈值”中的值,则将“a”、“b”和“c”列中的值替换为 NA。我需要逐行进行。
如果我做得对,df 将如下所示:
a b c threshold
1 NA NA NA 0.19
2 NA NA NA 0.97
3 0.16 0.11 0.35 1.34
4 0.03 0.04 0.10 1.50
5 0.23 NA NA 0.45
6 NA NA 0.17 0.30
7 0.28 NA NA 0.56
我也尝试过 apply() 方法,但无济于事。请问可以帮忙吗??
解决方案
您应该dplyr
在大多数此类用例中使用。下面的一种方法:
> set.seed(10)
> df <- data.frame(a = rnorm(7), b = rnorm(7), c = rnorm(7), threshold = rnorm(7))
> df <- round(abs(df), 2)
> df
a b c threshold
1 0.02 0.36 0.74 2.19
2 0.18 1.63 0.09 0.67
3 1.37 0.26 0.95 2.12
4 0.60 1.10 0.20 1.27
5 0.29 0.76 0.93 0.37
6 0.39 0.24 0.48 0.69
7 1.21 0.99 0.60 0.87
>
> df %>%
+ mutate_at(vars(a:c), ~ifelse(.x > df$threshold, NA, .x))
a b c threshold
1 0.02 0.36 0.74 2.19
2 0.18 NA 0.09 0.67
3 1.37 0.26 0.95 2.12
4 0.60 1.10 0.20 1.27
5 0.29 NA NA 0.37
6 0.39 0.24 0.48 0.69
7 NA NA 0.60 0.87
推荐阅读
- karate - 如何通过在使用空手道的 API 测试的 GET URL 中将 ID 作为参数应用来一次获取一个动态 ID 列表
- css - 将 SVG SMIL 线性渐变动画转换为 CSS 动画
- java - Gradle 项目构建失败
- javascript - 未捕获的 NotFoundError
- android - 范围可组合物到父可组合物
- node.js - 我的环境变量会暴露给浏览器吗?
- r - 使用 R 中变量之间的相关值制作矩形矩阵热图
- javascript - 我网站上 scrollIntoView 的奇怪行为
- javascript - 为什么我允许位置权限后不能设置状态值(如果我允许位置权限,默认值为当前位置)?
- javascript - 即使在 React 中具有初始状态,状态也未定义