在R中使用循环计算

时间:2018-04-26 07:33:08

标签: r loops

考虑以下数据框:

x1 <- matrix(c(100,200,300,500),ncol=1,dimnames=list(LETTERS[1:4],"x"))
y1 <- matrix(c(75,100,300,400),ncol=1,dimnames=list(LETTERS[1:4],"y"))
datamichael <- data.frame(x1,y1)
x2 <- matrix(c(200,50,200,600),ncol=1,dimnames=list(LETTERS[1:4],"x"))
y2 <- matrix(c(100,100,400,300),ncol=1,dimnames=list(LETTERS[1:4],"y"))
dataewan <- data.frame(x2,y2)
x3 <- matrix(c(100,150,400,200),ncol=1,dimnames=list(LETTERS[1:4],"x"))
y3 <- matrix(c(100,100,400,300),ncol=1,dimnames=list(LETTERS[1:4],"y"))
datatom <- data.frame(x3,y3)

我已将这三个data.frame合并为:

datamichaeldataewan <- rbind(datamichael,dataewan)
datamichaeldatatom <- rbind(datamichael,datatom)

使用包Benchmarking我想进行以下计算:

library(Benchmarking)
effmichaelewan <- dea(data.frame(datamichaeldataewan[1]),
                      data.frame(datamichaeldataewan[2]),
                      RTS="crs", ORIENTATION="out",
                      XREF=datamichael$x1, YREF=datamichael$y1)
effmichaeltom <- dea(data.frame(datamichaeldatatom[1]),
                     data.frame(datamichaeldatatom[2]),
                     RTS="crs", ORIENTATION="out",
                     XREF=datamichael$x1, YREF=datamichael$y1)

我的问题是我有两个以上的合并data.frame。那么可以通过循环进行上面的计算吗?重要的是输出变量的名称是“eff [name-after-first-data] [name-after-second-data]”。并且:datamichaeldataewan在每次计算中发生变化:

dea(data.frame(datamichaeldataewan[1]),
    data.frame(datamichaeldataewan[2]),
    RTS="crs", ORIENTATION="out",
    XREF=datamichael$x1, YREF=datamichael$y1)

1 个答案:

答案 0 :(得分:1)

如果将合并的数据框存储在列表中,则可以轻松重写。

使用dataframelist存储在rbinddatamichael以及lapply

datalist <- list(dataewan = dataewan, datatom = datatom)
datalist <- lapply(datalist, function(x) rbind(datamichael, x))
names(datalist) <- paste0("datamichael", names(datalist))

使用lapply计算结果:

efflist <- lapply(datalist, function(x) 
  dea(data.frame(x[1]), data.frame(x[2]), RTS="crs", ORIENTATION="out", 
      XREF=datamichael$x1, YREF=datamichael$y1)) 
names(efflist) <- paste0("eff", gsub("data", "", names(efflist)))

efflist
# $effmichaelewan
#     A     B     C     D    A1    B1    C1    D1 
# 2.667 4.000 2.000 2.500 4.000 1.000 1.000 4.000 
# 
# $effmichaeltom
#     A     B     C     D    A1    B1    C1    D1 
# 2.000 3.000 1.500 1.875 1.500 2.250 1.500 1.000