我有一个data.frames列表,其示例可以在下面的example.data中找到
example.data <- list(
stage1 <- data.frame(stuff=c("Apples","Oranges","Bananas"),
Prop1=c(1,2,3),
Prop2=c(3,2,1),
Wt=c(1,2,3)),
stage2 <- data.frame(stuff=c("Bananas","Mango","Cherry","Quince","Gooseberry"),
Prop1=c(8,9,10,1,2),
Prop2=c(23,32,55,5,4),
Wt=c(45,23,56,99,2)),
stage3 <- data.frame(stuff=c("Gooseberry","Bread","Grapes","Butter"),
Prop1=c(9,8,9,10),
Prop2=c(34,45,67,88),
Wt=c(24,56,31,84))
)
data.frames将始终具有相同的列数,但它们的行会有所不同,列表中的data.frames数也会有所不同。注意通过列表苹果链到香蕉,香蕉去醋栗和醋栗去黄油。也就是说,每对data.frames都有一个共同的元素。
我想在整个列表中按比例放大权重,如下所示。首先,我需要输入我的最终体重,比如20e3。其次,我需要最后一行的比例因子,最后一个数据帧的最后一列:在这种特殊情况下,对于最后一个数据帧,这将是20e3 / 84。我想在某个时刻使用这个比例因子来在最后一个数据帧中创建新列。
接下来,我想在最后一个数据帧和前一个数据帧之间进行缩放。因此,使用先前计算的比例因子,stage2的输入为(24 * 20e3 / 84)/ 2,即stage3 Gooseberry的权重乘以相对于20e3的比例因子除以stage2 Gooseberry权重,得到新的比例因子。重复该过程(通过香蕉)以给出阶段1比例因子。
在这个特定的例子中,阶段1阶段2阶段3的比例因子应为42858.0 2857.2 238.1。
在提取每个data.frame的最后一个元素的坐标后,我尝试使用适当的子设置在列表长度的反向上执行for循环。这失败了,因为for循环不同步。我不愿发布我试过的内容,以防我误导任何人。
没有得到很多回复,所以这就是我到目前为止所做的...
last.element <- function(a.list) {
## The function finds the last element in a list of dataframes which
a <- length(a.list) ## required to subset the last element
x <- dim(a.list[[a]])[1]
y <- dim(a.list[[a]])[2]
details <- c(a,x,y)
return(details)
}
details <- as.data.frame(matrix(,nrow=length(example.data),ncol=3))
for (i in length(example.data):1) {
details[i,1:3] <- last.element(example.data[1:i])
}
该函数给出列表中每个data.frames中的最后一个元素。我已经设置了一个data.frame,我想用比例因子填充。接着,
details[,4] <- 1
for (i in length(example.data):1) {
details[i,4] <- 20e3 / as.numeric(example.data[[i]][as.matrix(details[i,2:3])])
}
我在详细data.frame中设置了一个额外的列,为扩展因子做好准备。但for循环只给出了最后一个比例因子,
> details
V1 V2 V3 V4
1 1 3 4 6666.6667
2 2 5 4 10000.0000
3 3 4 4 238.0952
如果我将238.0952乘以84,它将给我20000。
但是第二个数据帧的比例因子应该是(24 * 238.0952)/ 2,即......第三个数据帧中的所有权重都乘以比例因子。通过将第三个data.frame中的缩放的Gooseberry值除以第二个data.frame中的Gooseberry值来导出新的比例因子。第一个数据帧的比例因子以类似的方式找到。