A functional approach in R to apply a function to a data frame that uses input from each column of another data frame

huangapple go评论68阅读模式
英文:

A functional approach in R to apply a function to a data frame that uses input from each column of another data frame

问题

Sure, here is the translation of the code-related content:

我想对数据帧中的所有元素应用线性逼近,基于查找表。

我能够为一个查找表执行此操作,但我需要一种功能性方法(即 mapapply)来多次应用此操作,用于多个写入一个数据帧的查找表。

我有数据帧 A,如下所示

A <- data.frame(cbind(c(2,2,1),c(1,1,2),c(2,1,2)))

和一个查找值表 Z

Z <- data.frame(cbind(c(1,2),c(0.25,0.5)))

我希望将其用作数据帧 A 中值的线性插值的基础。

我可以编写一个函数,根据 Z 中的值来插值 A 中的值,如下所示

approximate <- function(x) approx(x=Z[,1], y=Z[,2], xout=x)$y

并将其应用于 A 中的所有元素

library(purrr)
as.data.frame(purrr::map(A, approximate))

对于 Z 中的多列,例如

Z1 <- data.frame(cbind(c(1,2),c(0.25,0.5),c(0.5,1)))

期望的输出将是包含两个数据帧的两个列表,每个列表都为大小为 A 的数据帧,应用 Z1[,-1] 的每一列的 approximate 函数,即 c(0.25,0.5), c(0.5,1), ...

英文:

I want to apply a linear approximation to all elements in a data frame based on a lookup table.

I am able to do this for one lookup table, but I would need a functional approach (i.e. map or apply) to apply this multiple times for a number of lookup tables, which are written in one data frame.

I have data frame A, such that

A &lt;- data.frame(cbind(c(2,2,1),c(1,1,2),c(2,1,2)))

and a table of lookup values Z

Z &lt;- data.frame(cbind(c(1,2),c(0.25,0.5)))

which I want to use as basis for linear interpolation for values in data frame A.

I can write a function that interpolates the values in A based on values in Z, such that

approximate &lt;- function(x) approx(x=Z[,1], y=Z[,2], xout=x)$y

and apply it to the all elements in A

library(purrr)
as.data.frame(purrr::map(A, approximate))

How would I do this for more than one columns in Z, for example

Z1 &lt;- data.frame(cbind(c(1,2),c(0.25,0.5),c(0.5,1)))

The desired output would be two lists that each contain a data frame of size A that applies the approximate function for each column of Z1[,-1], c(0,25,0.5), c(0.5,1), ....

答案1

得分: 0

你可以修改你的 approximate() 函数,包括一个参数用于指定要用于 yZ1[, -1] 的哪一列。然后,你可以在 Z1[, -1] 上使用外部的 map(),在 A 上使用内部的 map_dfr()(在这个上下文中等同于 as.data.frame(map()))。例如:

library(purrr)

approximate <- function(xout, y, x) approx(x, y, xout)$y

map(Z1[, -1], function(y) map_dfr(A, approximate, y, Z1[, 1]))
英文:

You can change your approximate() function to include an argument for which column of Z1[, -1] to use for y. You can then have an outer map() over Z1[, -1] and an inner map_dfr() (equivalent to as.data.frame(map()) in this context) over A. For example:

library(purrr)

approximate &lt;- function(xout, y, x) approx(x, y, xout)$y
    
map(Z1[, -1], function(y) map_dfr(A, approximate, y, Z1[, 1]))

huangapple
  • 本文由 发表于 2023年3月9日 20:11:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75684441.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定