【问题标题】:Passing dataframe rows into R functionsPassing dataframe rows into R functions
【发布时间】:2023-02-25 06:02:10
【问题描述】:

我知道以前有人问过这个问题,但我无法得到适合我的答案。我正在尝试使用 PearsonDS 的 dpearson 函数生成几条高斯曲线。一个简单的玩具示例:

library(PearsonDS)
moments <- c(mean=1,variance=2,skewness=1,kurtosis=5)
dpearson(seq(-2,3,by=1),moments=moments)

所以它需要一个 x 值向量和一个 5 个参数长的矩列表。

我想生成 7 条曲线并首先创建一个包含我所有时刻的矩阵:

df = data.frame( 
            mean = c(-6,-4,-2,0,2,4,6),
            variance = c(1,1,1,1,1,1,1),
            skewness = c(-2, -1, -0.5, 0, 0.5, 1, 2),
            kurtosis = c(7, 3, 1, 0, 1, 3, 7))

我还希望曲线沿 x 交错排列,因此我使用函数创建以曲线均值为中心的不同 x 值:

x = Map(seq, df$mean-3, df$mean+3)

但是,即使我只对 x (x[[1]]) 使用一组值,我也无法成功地将我的 df 作为参数输入到 dpearson 函数中。我尝试了各种形式的 lapply 和 apply 例如:

apply(df,1,dpearson(x[[1]],moments=df)

但如果我在应用之外指定第一行,我只能让它工作:

dpearson(x[[1]],moments=df[1,]

所以我的问题是,如何编写一个函数来接受 x 和 df 的每一行作为 dpearson 参数的输入?如果我可以让 x 向量取决于 df 的平均值,那也很好,例如

function{
x = Map(seq, d$mean-3, d$mean+3)
Curves = dpearson(x,moments=df) # where it does row-wise calculations for both x and df
}

感谢您的帮助。

【问题讨论】:

  • 它来自 PearsonDS 包
  • apply(df,1,\(y)dpearson(x[[1]],moments=y))
  • @onyambu 上面为我标记了一个错误

标签: r


【解决方案1】:

在使用 data.frames 时,我会避免使用 apply。您可以使用 Map 映射多个列表。我们可以使用 asplit 将您的 data.frames 转换为行值列表 (see other methods)。这种策略应该有效

Map(dpearson, 
  Map(seq, df$mean-3, df$mean+3), 
  asplit(df, 1)
)

【讨论】:

  • 我收到错误 a do call error 'what' must be a function or character string
猜你喜欢
  • 2022-11-20
  • 2022-12-02
  • 2022-12-02
  • 1970-01-01
  • 2022-12-26
  • 2022-12-02
  • 2022-12-01
  • 2022-12-01
  • 2022-12-01
相关资源
最近更新 更多