【问题标题】:How to find approximately close values in different number of rows from two dataframe?如何从两个数据框中找到不同行数的近似接近值?
【发布时间】:2019-06-19 13:42:37
【问题描述】:

我有两个数据框,一个有 24 行*2 列,另一个有 258 行*2 列。列相似,我对一列感兴趣,想在两个数据框中找到彼此近似接近的值?

我正在尝试模拟光谱并与实验进行比较。

df_exp <- data.frame("Name"=c(exp,Int), "exp" = c(x1, x2, x3, ...,x258),"int"= c(y1,y2,y3,...,y258))

df_sim <- data.frame("Name"=c(sim,Int), "sim" = c(x1, x2, x3, ...,x24),"int" = c(y1,y2,y3,...,y24))

初始值(来自df_expexp 列和来自df_simsim 列):

exp             sim     
206.0396    182.0812        
207.1782    229.1183        
229.0776    246.1448        
232.1367    302.1135        
241.1050    319.1401        
246.1691    357.1769        
250.0235    374.2034
...             ...

我试过这个 r 代码

match(df_exp$exp[1:258], df_sim$sim[1:24], nomatch = 0)         

这个代码给了我所有的零值,因为没有完全匹配。数字总是在小数位上有所不同。我试图将数字四舍五入到零小数位,并找到接近的值。但这不是我的意图。我想找到df_exp(229.0776,246.1691,...)df_sim(229.1183, 246.1448,...) 并使用所有这些近似接近的值创建一个新数据框。你能建议一些帮助吗?

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    您可以定义相似性截止值并在它们上循环:

    ### define your cutoff for similarity
    cutoff <- 0.01
    ### initialize vectors to store the similar values
    similar_sim <- vector(); similar_exp <- vector();
    ### open loop over both DF values
    for (sim_value in df_sim$sim) {
      for (exp_value in df_exp$exp) {
        ### if similar (< cutoff) append values to vectors
        if ( abs(sim_value - exp_value) < cutoff ) {
          similar_sim <- append(similar_sim, sim_value)
          expilar_exp <- append(expilar_exp, exp_value)
        }
      }
    }
    ### recreate a DF with the similar values
    similar_df <- as.data.frame(cbind(similar_sim, similar_exp))
    

    如果您想保存一个类似于另一个值的每个值,就像听起来一样。否则,您可以跳过循环并使用范围选择,例如:

    x[ x < x+cutoff & x > x-cutoff ]
    

    【讨论】:

    • 感谢您的帮助。我从以前的帖子中找到了解决方案,并尝试了对我有用的方法。 a=df$mz_sim b=df$mz_exp 切割
    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 2020-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    相关资源
    最近更新 更多