首页 > 解决方案 > 如何在R中对具有多个条件的值进行排序和提取?

问题描述

我有一个基本的条件数据提取问题。我已经用 Python 编写了代码。我正在学习 R;我想在 R 中复制相同的代码。

我尝试使用 which 放置条件参数,但这似乎不起作用。我还没有完全精通 R 语法。

我有一个包含 2 列的数据框:x 和 y 这个想法是提取一个最大 5 个 x 值乘以 2 的列表,对应于最大 y 值,条件是我们将只选择那些至少为 y 的值y 值峰值的 0.45 倍。

因此,该算法将具有以下步骤:

  1. 我们找到 y 的峰值:max_y

  2. 我们定义阈值 = 0.45 * max_y

  3. 我们应用一个过滤器,以获取所有大于阈值的 y 值的列表:y_filt

  4. 我们在步骤 3 中得到一个与 y 值对应的 x 值列表: x_filt

  5. 如果 x_filt 中的值的数量小于或等于 5,那么我们的结果将是 x_filt 中的值乘以 2

  6. 如果 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 中做同样的事情。

标签: pythonrdataframe

解决方案


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_filtx_filt,您可以在事后轻松创建它们:

y_filt <- df_filt$y
x_filt <- df_filt$x

请注意,如果您的最大值不是唯一的,like numpy.argmax,将返回多个值。which(df$y == max(y))


推荐阅读