R 在没有循环的数据帧中,如何通过该级别中另一个因子的子集操作该因子级别中的数据

R 在没有循环的数据帧中,如何通过该级别中另一个因子的子集操作该因子级别中的数据,r,loops,dplyr,plyr,R,Loops,Dplyr,Plyr,我有一个由多个样品(样品a、b、c、d)的吸收光谱组成的数据框架,其中Ydata是波长,Xdata是吸收。我通过减去远离感兴趣的峰值的安静波长范围内的平均吸收来计算基线校正吸收 简化数据帧: DF <- data.frame( group = rep(c("a", "b", "c", "d"),each=10), Ydata = rep(1:10, times = 4), Xdata = c(seq(1,10,1),seq(5,50,5),seq(20,11,-1),seq(0

我有一个由多个样品(样品a、b、c、d)的吸收光谱组成的数据框架,其中Ydata是波长,Xdata是吸收。我通过减去远离感兴趣的峰值的安静波长范围内的平均吸收来计算基线校正吸收

简化数据帧:

DF <- data.frame(
  group = rep(c("a", "b", "c", "d"),each=10),
  Ydata = rep(1:10, times = 4),
  Xdata = c(seq(1,10,1),seq(5,50,5),seq(20,11,-1),seq(0.3,3,0.3)),
  abscorr = NA
)

DF我相信这样就可以了

fun <- function(x){
    x$Xdata - mean(x[which(x$Ydata > 4 & x$Ydata < 8), "Xdata"])
}
DF$abscorr <- do.call(c, lapply(split(DF, DF$group), fun))
如您所见,
abscorr
的计算值没有差异,只是属性不同。其中,
na.omit
属性或
行名
存在差异。如果我是你,我不会担心,因为
abscorr
的值是相等的

编辑。
请注意,如果我排序
DF
,然后将问题属性设置为
NULL
这两个
all.equal
和更严格的
equality
返回
TRUE

DF1 <- DF[order(DF$group, DF$Ydata), ]  # Modify a copy, keep the original
row.names(DF1) <- NULL
attr(DF1, "na.action") <- NULL

all.equal(DF1, DF2)
#[1] TRUE
identical(DF1, DF2)
#[1] TRUE

DF1Try
dplyr

DF %>%
    group_by(group) %>%
    mutate(abscorr = Xdata - mean(Xdata[Ydata < 8 & Ydata > 4]))
DF%>%
分组依据(分组)%>%
突变(abscorr=Xdata-平均值(Xdata[Ydata<8&Ydata>4]))

谢谢!工作是一种享受。我无法理解dplyr包是如何工作的。谢谢Rui-一个很好的base-R解决方案!
fun <- function(x){
    x$Xdata - mean(x[which(x$Ydata > 4 & x$Ydata < 8), "Xdata"])
}
DF2 <- DF
DF2$abscorr <- do.call(c, lapply(split(DF2, DF2$group), fun))

all.equal(DF[order(DF$group, DF$Ydata), ], DF2)
# [1] "Attributes: < Names: 1 string mismatch >"                                         
# [2] "Attributes: < Length mismatch: comparison on first 2 components >"                
# [3] "Attributes: < Component 2: names for target but not for current >"                
# [4] "Attributes: < Component 2: Attributes: < Modes: list, NULL > >"                   
# [5] "Attributes: < Component 2: Attributes: < Lengths: 1, 0 > >"                       
# [6] "Attributes: < Component 2: Attributes: < names for target but not for current > >"
# [7] "Attributes: < Component 2: Attributes: < current is not list-like > >"            
# [8] "Attributes: < Component 2: target is omit, current is numeric >"                  
# [9] "Component “abscorr”: Modes: numeric, logical"                                     
#[10] "Component “abscorr”: target is numeric, current is logical"
DF1 <- DF[order(DF$group, DF$Ydata), ]  # Modify a copy, keep the original
row.names(DF1) <- NULL
attr(DF1, "na.action") <- NULL

all.equal(DF1, DF2)
#[1] TRUE
identical(DF1, DF2)
#[1] TRUE
DF %>%
    group_by(group) %>%
    mutate(abscorr = Xdata - mean(Xdata[Ydata < 8 & Ydata > 4]))