【问题标题】:R: Selecting every two consecutive rows for ddplyrR:为 dplyr 选择每两个连续的行
【发布时间】:2023-03-17 09:53:02
【问题描述】:

这是我的数据

 Assay Sample Dilution  meanresp number
    1    S     0.25       68.55      1
    1    S     0.50       54.35      2
    1    S     1.00       44.75      3

我的最终目标是对每两个连续的行应用线性回归,并使用 Dilution 和 meanresp 返回该回归的斜率。

表格的长度可能会有所不同,我不想使用 for 循环,因为我正试图摆脱这种习惯。

我认为 ddply 会很好,但我不确定如何选择每两个连续行的子集。我想也许有一种方式可以说'对长度为 2 的稀释的每个向量子集都这样做?

任何见解都会有所帮助。

【问题讨论】:

  • 我不确定您期望的结果。类似diff(meanresp) / diff(Dilution)(按AssaySample 分组)?
  • 可以this 帮助你吗? (用于每两个连续行的选择)
  • 我的目标是这样做:ddply(.data=data, .variables='subsets each continuous 2 rows', .fun='linear model function')有麻烦了这有意义吗?
  • ddply 按列而不是行拆分,因此您不能使用它。在下面两次使用lapply 检查一种方法。本质上你可以将这两个合并为 1 个函数,但我会避免它,因为它会导致难以阅读的代码。

标签: r statistics plyr apply linear-regression


【解决方案1】:

我不知道这对线性回归有何帮助,但您可以这样做:

df <- read.table(header=T, text="Assay Sample Dilution  meanresp number
    1    S     0.25       68.55      1
    1    S     0.50       54.35      2
    1    S     1.00       44.75      3")

使用lapply

> lapply(2:nrow(df), function(x) df[(x-1):x,] )
[[1]]
  Assay Sample Dilution meanresp number
1     1      S     0.25    68.55      1
2     1      S     0.50    54.35      2

[[2]]
  Assay Sample Dilution meanresp number
2     1      S      0.5    54.35      2
3     1      S      1.0    44.75      3

如果您还想要连续行的特定列,您可以将它们选择为:

> lapply(2:nrow(df), function(x) df[(x-1):x, c('Dilution','meanresp')] )
[[1]]
  Dilution meanresp
1     0.25    68.55
2     0.50    54.35

[[2]]
  Dilution meanresp
2      0.5    54.35
3      1.0    44.75

编辑

如果您想执行线性回归,另一个lapply 就足够了:

a <- lapply(2:nrow(df), function(x) df[(x-1):x, c('Dilution','meanresp')] )

b <- lapply(a,function(x) lm(Dilution~meanresp,data=x))

>b
[[1]]

Call:
lm(formula = Dilution ~ meanresp, data = x)

Coefficients:
(Intercept)     meanresp  
    1.45687     -0.01761  


[[2]]

Call:
lm(formula = Dilution ~ meanresp, data = x)

Coefficients:
(Intercept)     meanresp  
    3.33073     -0.05208  

或者如果你只想要坡度:

b <- lapply(a, function(x) {
                    d <- lm(Dilution~meanresp,data=x)
                    coefficients(summary(d))[2,1]
})

> b
[[1]]
[1] -0.01760563

[[2]]
[1] -0.05208333

【讨论】:

  • 这太好了,谢谢。它几乎完全符合我的需要(我只需要将列表变成数据框,而不是显示使用的稀释度)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-23
  • 1970-01-01
  • 2018-06-26
  • 1970-01-01
相关资源
最近更新 更多