我有一个数据框,如下所示:
dput(head(modellingdata, n = 5))
structure(list(X = 1:5, heading = c(2, 0.5, 2, 1.5, 2), StartFrame = c(27L,
28L, 24L, 31L, 35L), StartYaw = c(0.0719580421911421, 0.0595571128205128,
0.0645337707459207, 0.0717132524475524, 0.066818187062937), FirstSteeringTime = c(0.433389999999999,
0.449999999999989, 0.383199999999988, 0.499899999999997, 0.566800000000001
), pNum = c(1L, 1L, 1L, 1L, 1L), EarlyResponses = c(FALSE, FALSE,
FALSE, FALSE, FALSE), PeakFrame = c(33L, 34L, 32L, 38L, 46L),
PeakYaw = c(0.201025641025641, 0.140734297249417, 0.187890472913753,
0.154032698135198, 0.23129368951049), PeakSteeringTime = c(0.533459999999998,
0.550099999999986, 0.516700000000014, 0.616600000000005,
0.750100000000003), heading_radians = c(0.0349065850398866,
0.00872664625997165, 0.0349065850398866, 0.0261799387799149,
0.0349065850398866), error_rate = c(2.86537083478438, 11.459301348013,
2.86537083478438, 3.82015500141104, 2.86537083478438), error_growth = c(0.34899496702501,
0.0872653549837393, 0.34899496702501, 0.261769483078731,
0.34899496702501)), row.names = c(NA, 5L), class = "data.frame")
我df的每一行都是试用版。总体而言,我有3037行(试用版)。 pNum表示参与者人数-我总共有19位参与者。
我还为每个参与者提供了一个截距数据框:
dput(head(heading_intercept, n = 19))
c(0.432448612242496, 0.446371667203615, 0.420854119185846, 0.366763485495426,
0.355619586392715, 0.381658477093055, 0.512552445721875, 0.317210665852951,
0.358345666677048, 0.421441965798511, 0.477135103908373, 0.325512003640487,
0.5542144068862, 0.454182438162137, 0.333993738757344, 0.424179318544432,
0.272486598058728, 0.37014581658542, 0.397112817663261)
我想做的是在我的modellingdata数据框中创建一个新列“ intercept”。如果pNum为1,我想在heading_intercept数据帧中选择第一个截距,然后为pNum为1的每一行输入该值。当pNum为2时,我想向pNum为2的每一行输入第二个截距值。等等...
我已经尝试过了:
for (i in c(1:19)){
if (modellingdata$pNum == i){
modellingdata$intercept <- c(heading_intercept[i])
}
}
但是,这只是为每行和每个pNum输入第一个heading_intercept值。有人有什么想法吗?任何帮助表示赞赏!
答案 0 :(得分:1)
modellingdata$intercept <- heading_intercept[modellingdata$pNum]
或对当前循环进行最小程度的修改:
modellingdata$intercept <- 0L
for (i in c(1:19)){
rows <- modellingdata$pNum == i
if (any(rows)) {
modellingdata$intercept[rows] <- heading_intercept[i]
}
}