python - 如何在R中对具有多个条件的值进行排序和提取?
问题描述
我有一个基本的条件数据提取问题。我已经用 Python 编写了代码。我正在学习 R;我想在 R 中复制相同的代码。
我尝试使用 which 放置条件参数,但这似乎不起作用。我还没有完全精通 R 语法。
我有一个包含 2 列的数据框:x 和 y 这个想法是提取一个最大 5 个 x 值乘以 2 的列表,对应于最大 y 值,条件是我们将只选择那些至少为 y 的值y 值峰值的 0.45 倍。
因此,该算法将具有以下步骤:
我们找到 y 的峰值:max_y
我们定义阈值 = 0.45 * max_y
我们应用一个过滤器,以获取所有大于阈值的 y 值的列表:y_filt
我们在步骤 3 中得到一个与 y 值对应的 x 值列表: x_filt
如果 x_filt 中的值的数量小于或等于 5,那么我们的结果将是 x_filt 中的值乘以 2
如果 x_filt 的值超过 5 个,我们只选择列表中 5 个最大 y 值对应的 5 个值。然后我们乘以 2 得到我们的结果
Python代码
max_y = max(y)
max_x = x[y.argmax()]
print (max_x, max_y)
threshold = 0.45 * max_y
y_filt = y [y > threshold]
x_filt = x [y > threshold]
if len(y_filt) > 4:
n_highest = 5
else:
n_highest = len(y_filt)
y_filt_highest = y_filt.argsort()[-n_highest:][::-1]
result = [x_filt[i]*2 for i in range(len(x_filt)) if i in y_filt_highest]
例如数据集
x y
1 20
2 7
3 5
4 11
5 0
6 8
7 3
8 10
9 2
10 6
11 15
12 18
13 0
14 1
15 12
上面的代码将给出以下结果
max_y = 20
max_x = 1
threshold = 9
y_filt = [20, 11, 10, 15, 18, 12]
x_filt = [1, 4, 8, 11, 12, 15]
n_highest = 5
y_filt_highest = [20, 11, 15, 18, 12]
result = [2, 8, 22, 24, 30]
我希望在 R 中做同样的事情。
解决方案
R 在统计工作中如此强大/易于使用的原因之一是内置data.frame
是基础。在这里使用一个可以简化事情:
# Create a dataframe with the toy data
df <- data.frame(x = 1:10, y = c(20, 7, 5, 11, 0, 8, 3, 10, 2, 6))
# Refer to columns with the $ notation
max_y <- max(df$y)
max_x <- df$x[which(df$y == max_y)]
# If you want to print both values, you need to create a list with c()
print(c(max_x, max_y))
# But you could also just call the values directly, as in python
max_x
max_y
# Calculate a threshold and then create a filtered data.frame
threshold <- 0.45 * max_y
df_filt <- df[which(df$y > threshold), ]
df_filt <- df_filt[order(-df_filt$y), ]
if(nrow(df_filt) > 5){
df_filt <- df_filt[1:5, ]
}
# Calculate the result
result <- df_filt$x * 2
# Alternatively, you may want the result to be part of your data.frame
df_filt$result <- df_filt$x*2
# Should show identical results
max_y
max_x
threshold
df_filt # Probably don't want to print a df if it is large
result
当然,如果您真的需要单独的向量y_filt
和x_filt
,您可以在事后轻松创建它们:
y_filt <- df_filt$y
x_filt <- df_filt$x
请注意,如果您的最大值不是唯一的,like numpy.argmax
,将返回多个值。which(df$y == max(y))
推荐阅读
- javascript - 如何使用 Chrome.storage Chrome 扩展程序保存数据 [MV2]
- c# - 如何使用现有的 PDB 文件反编译我的 DLL 文件以恢复我的代码以便识别?
- android - minifiyEnabled 在 android 启动屏幕后导致应用程序崩溃
- c# - 生成链接以确认电子邮件在 ASP.NET Core API 中返回 null
- azure - 如何使用 Azure AD B2C 作为 Amazon Cognito 的 IdP
- java - maven 多级继承排除
- excel - Excel,VBA:替换从 Excel 输入框中获得的变量中的字符串
- java - 在customListener的情况下Spring批处理重试问题
- python - 从文件中读取的数据与看似相同的字符串不匹配
- css - 仅在移动设备上的 translateY 动画期间具有 scaleX(-1) 的元素消失