第一种
> mydata <- data.frame(x1 = c(2,2,6,4),x2 = c(3,4,2,8)) > mydata x1 x2 1 2 3 2 2 4 3 6 2 4 4 8 > mydata$sumx <- mydata$x1 + mydata$x2 > mydata x1 x2 sumx 1 2 3 5 2 2 4 6 3 6 2 8 4 4 8 12 > mydata$meanx <- (mydata$x1 + mydata$x2)/2 > mydata x1 x2 sumx meanx 1 2 3 5 2.5 2 2 4 6 3.0 3 6 2 8 4.0 4 4 8 12 6.0
第二种
> attach(mydata) ##解放mydata中的变量x1和x2,以便后续直接调用 The following object is masked _by_ .GlobalEnv: meanx > mydata$sumx2 <- x1 + x2 > mydata x1 x2 sumx meanx sumx2 1 2 3 5 2.5 5 2 2 4 6 3.0 6 3 6 2 8 4.0 8 4 4 8 12 6.0 12 > mydata$meanx2 <- (x1+2)/2 > mydata x1 x2 sumx meanx sumx2 meanx2 1 2 3 5 2.5 5 2 2 2 4 6 3.0 6 2 3 6 2 8 4.0 8 4 4 4 8 12 6.0 12 3 > detach(mydata)
第三种
> mydata <- transform(mydata,sumx3 = x1 + x2, meanx3 = (x1 + x2)/2) ##为啥可以在transform()中直接调用x1和x2呢?? > mydata x1 x2 sumx meanx sumx2 meanx2 sumx3 meanx3 1 2 3 5 2.5 5 2 5 2.5 2 2 4 6 3.0 6 2 6 3.0 3 6 2 8 4.0 8 4 8 4.0 4 4 8 12 6.0 12 3 12 6.0