两个不等大小的数据帧之间的欧几里德距离

时间:2018-05-02 19:28:33

标签: r dataframe distance

我有两个大小不等的数据框:

>df1

    b  c  d
a   2  3  4

>df2

   g  h  i
e  1  1  5
f  0  4  3

我需要通过从df1中的每一行中减去df2中包含的值来计算这些数据帧的元素之间的欧几里德距离,因此我想得到:

   c  d  e
a  1  2  1
b  2  1  1

由于尺寸不等,尝试>myfunc1 <- function(x1,x2){abs(x1 - x2)} myfunc1(df1, df2)以及df3 <- abs(df2 - df1)无济于事。

2 个答案:

答案 0 :(得分:1)

/** ExampleModel.kt */
@Entity(
    tableName = "examples",
    indices = [Index(value = arrayOf("name"), unique = true)]
)
class ExampleModel(): BaseModel() {

    @ColumnInfo(name = "name")
    @SerializedName(value = "name")
    var name: String = String()

    @Ignore
    constructor(name: String): this() {
        this@ExampleModel.name = name
    }

}


/** ExampleDAO.kt */
@Dao
interface ExampleDAO: BaseDAO<ExampleModel> {

    @Query("SELECT * FROM `examples`")
    override fun getAll(): List<ExampleModel>

}


/** AppDatabase.kt **/
@Database(entities = [ExampleModel::class], version = 1)
abstract class AppDatabase: RoomDatabase() {

    abstract fun exampleDAO(): ExampleDAO

    companion object {
        private var databaseInstance: AppDatabase? = null
        public const val DatabaseName: String = "app_database"

        fun getDatabase(context: Context): AppDatabase {
            this@Companion.destroyAndCreateNewInstanceIfNeeded(context)
            return this@Companion.databaseInstance!!
        }

        fun destroyAndCreateNewInstanceIfNeeded(context: Context) {
            synchronized(AppDatabase::class) {
                this@Companion.databaseInstance?.close()
                this@Companion.databaseInstance = Room.databaseBuilder(
                    context.applicationContext,
                    AppDatabase::class.java,
                    this@Companion.DatabaseName
                ).build()
            }
        }
    }

}

或Gregor的方法:require(purrr) map2_df(df1, df2, ~abs(.x - .y))

从我的有限测试中,abs(df2 - df1[rep(1, nrow(df2)), ])似乎更快

map2_df

enter image description here

答案 1 :(得分:0)

如果案例总是在第一个矩阵中有一行,则可以使用基础r apply方法:

Thread 16: ESC_BAD_ACCESS (code=1, address=0xfffffffffffffffc)
UITableView.scrollToRow(at:at:animated:) must be used from main thread only