Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

R

Views: 4030
Kernel: R (R-Project)
help(library)

Exercise 1

The code help(library) displays the Loading/Attaching and Listing of Packages. How to use the function.

library
function (package, help, pos = 2, lib.loc = NULL, character.only = FALSE, 
    logical.return = FALSE, warn.conflicts = TRUE, quietly = FALSE, 
    verbose = getOption("verbose")) 
{
    testRversion <- function(pkgInfo, pkgname, pkgpath) {
        if (is.null(built <- pkgInfo$Built)) 
            stop(gettextf("package %s has not been installed properly\n", 
                sQuote(pkgname)), call. = FALSE, domain = NA)
        R_version_built_under <- as.numeric_version(built$R)
        if (R_version_built_under < "3.0.0") 
            stop(gettextf("package %s was built before R 3.0.0: please re-install it", 
                sQuote(pkgname)), call. = FALSE, domain = NA)
        current <- getRversion()
        if (length(Rdeps <- pkgInfo$Rdepends2)) {
            for (dep in Rdeps) if (length(dep) > 1L) {
                target <- dep$version
                res <- if (is.character(target)) {
                  do.call(dep$op, list(as.numeric(R.version[["svn rev"]]), 
                    as.numeric(sub("^r", "", dep$version))))
                }
                else {
                  do.call(dep$op, list(current, as.numeric_version(target)))
                }
                if (!res) 
                  stop(gettextf("This is R %s, package %s needs %s %s", 
                    current, sQuote(pkgname), dep$op, target), 
                    call. = FALSE, domain = NA)
            }
        }
        if (R_version_built_under > current) 
            warning(gettextf("package %s was built under R version %s", 
                sQuote(pkgname), as.character(built$R)), call. = FALSE, 
                domain = NA)
        platform <- built$Platform
        r_arch <- .Platform$r_arch
        if (.Platform$OS.type == "unix") {
            if (!nzchar(r_arch) && length(grep("\\w", platform)) && 
                !testPlatformEquivalence(platform, R.version$platform)) 
                stop(gettextf("package %s was built for %s", 
                  sQuote(pkgname), platform), call. = FALSE, 
                  domain = NA)
        }
        else {
            if (nzchar(platform) && !grepl("mingw", platform)) 
                stop(gettextf("package %s was built for %s", 
                  sQuote(pkgname), platform), call. = FALSE, 
                  domain = NA)
        }
        if (nzchar(r_arch) && file.exists(file.path(pkgpath, 
            "libs")) && !file.exists(file.path(pkgpath, "libs", 
            r_arch))) 
            stop(gettextf("package %s is not installed for 'arch = %s'", 
                sQuote(pkgname), r_arch), call. = FALSE, domain = NA)
    }
    checkLicense <- function(pkg, pkgInfo, pkgPath) {
        L <- tools:::analyze_license(pkgInfo$DESCRIPTION["License"])
        if (!L$is_empty && !L$is_verified) {
            site_file <- path.expand(file.path(R.home("etc"), 
                "licensed.site"))
            if (file.exists(site_file) && pkg %in% readLines(site_file)) 
                return()
            personal_file <- path.expand("~/.R/licensed")
            if (file.exists(personal_file)) {
                agreed <- readLines(personal_file)
                if (pkg %in% agreed) 
                  return()
            }
            else agreed <- character()
            if (!interactive()) 
                stop(gettextf("package %s has a license that you need to accept in an interactive session", 
                  sQuote(pkg)), domain = NA)
            lfiles <- file.path(pkgpath, c("LICENSE", "LICENCE"))
            lfiles <- lfiles[file.exists(lfiles)]
            if (length(lfiles)) {
                message(gettextf("package %s has a license that you need to accept after viewing", 
                  sQuote(pkg)), domain = NA)
                readline("press RETURN to view license")
                encoding <- pkgInfo$DESCRIPTION["Encoding"]
                if (is.na(encoding)) 
                  encoding <- ""
                if (encoding == "latin1") 
                  encoding <- "cp1252"
                file.show(lfiles[1L], encoding = encoding)
            }
            else {
                message(gettextf("package %s has a license that you need to accept:\naccording to the DESCRIPTION file it is", 
                  sQuote(pkg)), domain = NA)
                message(pkgInfo$DESCRIPTION["License"], domain = NA)
            }
            choice <- menu(c("accept", "decline"), title = paste("License for", 
                sQuote(pkg)))
            if (choice != 1) 
                stop(gettextf("license for package %s not accepted", 
                  sQuote(package)), domain = NA, call. = FALSE)
            dir.create(dirname(personal_file), showWarnings = FALSE)
            writeLines(c(agreed, pkg), personal_file)
        }
    }
    checkNoGenerics <- function(env, pkg) {
        nenv <- env
        ns <- .getNamespace(as.name(pkg))
        if (!is.null(ns)) 
            nenv <- asNamespace(ns)
        if (exists(".noGenerics", envir = nenv, inherits = FALSE)) 
            TRUE
        else {
            length(objects(env, pattern = "^\\.__T", all.names = TRUE)) == 
                0L
        }
    }
    checkConflicts <- function(package, pkgname, pkgpath, nogenerics, 
        env) {
        dont.mind <- c("last.dump", "last.warning", ".Last.value", 
            ".Random.seed", ".Last.lib", ".onDetach", ".packageName", 
            ".noGenerics", ".required", ".no_S3_generics", ".Depends", 
            ".requireCachedGenerics")
        sp <- search()
        lib.pos <- match(pkgname, sp)
        ob <- objects(lib.pos, all.names = TRUE)
        if (!nogenerics) {
            these <- ob[substr(ob, 1L, 6L) == ".__T__"]
            gen <- gsub(".__T__(.*):([^:]+)", "\\1", these)
            from <- gsub(".__T__(.*):([^:]+)", "\\2", these)
            gen <- gen[from != package]
            ob <- ob[!(ob %in% gen)]
        }
        fst <- TRUE
        ipos <- seq_along(sp)[-c(lib.pos, match(c("Autoloads", 
            "CheckExEnv"), sp, 0L))]
        for (i in ipos) {
            obj.same <- match(objects(i, all.names = TRUE), ob, 
                nomatch = 0L)
            if (any(obj.same > 0)) {
                same <- ob[obj.same]
                same <- same[!(same %in% dont.mind)]
                Classobjs <- grep("^\\.__", same)
                if (length(Classobjs)) 
                  same <- same[-Classobjs]
                same.isFn <- function(where) vapply(same, exists, 
                  NA, where = where, mode = "function", inherits = FALSE)
                same <- same[same.isFn(i) == same.isFn(lib.pos)]
                not.Ident <- function(ch, TRAFO = identity, ...) vapply(ch, 
                  function(.) !identical(TRAFO(get(., i)), TRAFO(get(., 
                    lib.pos)), ...), NA)
                if (length(same)) 
                  same <- same[not.Ident(same)]
                if (length(same) && identical(sp[i], "package:base")) 
                  same <- same[not.Ident(same, ignore.environment = TRUE)]
                if (length(same)) {
                  if (fst) {
                    fst <- FALSE
                    packageStartupMessage(gettextf("\nAttaching package: %s\n", 
                      sQuote(package)), domain = NA)
                  }
                  msg <- .maskedMsg(same, pkg = sQuote(sp[i]), 
                    by = i < lib.pos)
                  packageStartupMessage(msg, domain = NA)
                }
            }
        }
    }
    if (verbose && quietly) 
        message("'verbose' and 'quietly' are both true; being verbose then ..")
    if (!missing(package)) {
        if (is.null(lib.loc)) 
            lib.loc <- .libPaths()
        lib.loc <- lib.loc[dir.exists(lib.loc)]
        if (!character.only) 
            package <- as.character(substitute(package))
        if (length(package) != 1L) 
            stop("'package' must be of length 1")
        if (is.na(package) || (package == "")) 
            stop("invalid package name")
        pkgname <- paste("package", package, sep = ":")
        newpackage <- is.na(match(pkgname, search()))
        if (newpackage) {
            pkgpath <- find.package(package, lib.loc, quiet = TRUE, 
                verbose = verbose)
            if (length(pkgpath) == 0L) {
                txt <- if (length(lib.loc)) 
                  gettextf("there is no package called %s", sQuote(package))
                else gettext("no library trees found in 'lib.loc'")
                if (logical.return) {
                  warning(txt, domain = NA)
                  return(FALSE)
                }
                else stop(txt, domain = NA)
            }
            which.lib.loc <- normalizePath(dirname(pkgpath), 
                "/", TRUE)
            pfile <- system.file("Meta", "package.rds", package = package, 
                lib.loc = which.lib.loc)
            if (!nzchar(pfile)) 
                stop(gettextf("%s is not a valid installed package", 
                  sQuote(package)), domain = NA)
            pkgInfo <- readRDS(pfile)
            testRversion(pkgInfo, package, pkgpath)
            if (!package %in% c("datasets", "grDevices", "graphics", 
                "methods", "splines", "stats", "stats4", "tcltk", 
                "tools", "utils") && isTRUE(getOption("checkPackageLicense", 
                FALSE))) 
                checkLicense(package, pkgInfo, pkgpath)
            if (is.character(pos)) {
                npos <- match(pos, search())
                if (is.na(npos)) {
                  warning(gettextf("%s not found on search path, using pos = 2", 
                    sQuote(pos)), domain = NA)
                  pos <- 2
                }
                else pos <- npos
            }
            .getRequiredPackages2(pkgInfo, quietly = quietly)
            deps <- unique(names(pkgInfo$Depends))
            if (packageHasNamespace(package, which.lib.loc)) {
                if (isNamespaceLoaded(package)) {
                  newversion <- as.numeric_version(pkgInfo$DESCRIPTION["Version"])
                  oldversion <- as.numeric_version(getNamespaceVersion(package))
                  if (newversion != oldversion) {
                    res <- try(unloadNamespace(package))
                    if (inherits(res, "try-error")) 
                      stop(gettextf("Package %s version %s cannot be unloaded", 
                        sQuote(package), oldversion, domain = "R-base"))
                  }
                }
                tt <- try({
                  ns <- loadNamespace(package, c(which.lib.loc, 
                    lib.loc))
                  env <- attachNamespace(ns, pos = pos, deps)
                })
                if (inherits(tt, "try-error")) 
                  if (logical.return) 
                    return(FALSE)
                  else stop(gettextf("package or namespace load failed for %s", 
                    sQuote(package)), call. = FALSE, domain = NA)
                else {
                  on.exit(detach(pos = pos))
                  nogenerics <- !.isMethodsDispatchOn() || checkNoGenerics(env, 
                    package)
                  if (warn.conflicts && !exists(".conflicts.OK", 
                    envir = env, inherits = FALSE)) 
                    checkConflicts(package, pkgname, pkgpath, 
                      nogenerics, ns)
                  on.exit()
                  if (logical.return) 
                    return(TRUE)
                  else return(invisible(.packages()))
                }
            }
            else stop(gettextf("package %s does not have a namespace and should be re-installed", 
                sQuote(package)), domain = NA)
        }
        if (verbose && !newpackage) 
            warning(gettextf("package %s already present in search()", 
                sQuote(package)), domain = NA)
    }
    else if (!missing(help)) {
        if (!character.only) 
            help <- as.character(substitute(help))
        pkgName <- help[1L]
        pkgPath <- find.package(pkgName, lib.loc, verbose = verbose)
        docFiles <- c(file.path(pkgPath, "Meta", "package.rds"), 
            file.path(pkgPath, "INDEX"))
        if (file.exists(vignetteIndexRDS <- file.path(pkgPath, 
            "Meta", "vignette.rds"))) 
            docFiles <- c(docFiles, vignetteIndexRDS)
        pkgInfo <- vector("list", 3L)
        readDocFile <- function(f) {
            if (basename(f) %in% "package.rds") {
                txt <- readRDS(f)$DESCRIPTION
                if ("Encoding" %in% names(txt)) {
                  to <- if (Sys.getlocale("LC_CTYPE") == "C") 
                    "ASCII//TRANSLIT"
                  else ""
                  tmp <- try(iconv(txt, from = txt["Encoding"], 
                    to = to))
                  if (!inherits(tmp, "try-error")) 
                    txt <- tmp
                  else warning("'DESCRIPTION' has an 'Encoding' field and re-encoding is not possible", 
                    call. = FALSE)
                }
                nm <- paste0(names(txt), ":")
                formatDL(nm, txt, indent = max(nchar(nm, "w")) + 
                  3)
            }
            else if (basename(f) %in% "vignette.rds") {
                txt <- readRDS(f)
                if (is.data.frame(txt) && nrow(txt)) 
                  cbind(basename(gsub("\\.[[:alpha:]]+$", "", 
                    txt$File)), paste(txt$Title, paste0(rep.int("(source", 
                    NROW(txt)), ifelse(nzchar(txt$PDF), ", pdf", 
                    ""), ")")))
                else NULL
            }
            else readLines(f)
        }
        for (i in which(file.exists(docFiles))) pkgInfo[[i]] <- readDocFile(docFiles[i])
        y <- list(name = pkgName, path = pkgPath, info = pkgInfo)
        class(y) <- "packageInfo"
        return(y)
    }
    else {
        if (is.null(lib.loc)) 
            lib.loc <- .libPaths()
        db <- matrix(character(), nrow = 0L, ncol = 3L)
        nopkgs <- character()
        for (lib in lib.loc) {
            a <- .packages(all.available = TRUE, lib.loc = lib)
            for (i in sort(a)) {
                file <- system.file("Meta", "package.rds", package = i, 
                  lib.loc = lib)
                title <- if (nzchar(file)) {
                  txt <- readRDS(file)
                  if (is.list(txt)) 
                    txt <- txt$DESCRIPTION
                  if ("Encoding" %in% names(txt)) {
                    to <- if (Sys.getlocale("LC_CTYPE") == "C") 
                      "ASCII//TRANSLIT"
                    else ""
                    tmp <- try(iconv(txt, txt["Encoding"], to, 
                      "?"))
                    if (!inherits(tmp, "try-error")) 
                      txt <- tmp
                    else warning("'DESCRIPTION' has an 'Encoding' field and re-encoding is not possible", 
                      call. = FALSE)
                  }
                  txt["Title"]
                }
                else NA
                if (is.na(title)) 
                  title <- " ** No title available ** "
                db <- rbind(db, cbind(i, lib, title))
            }
            if (length(a) == 0L) 
                nopkgs <- c(nopkgs, lib)
        }
        dimnames(db) <- list(NULL, c("Package", "LibPath", "Title"))
        if (length(nopkgs) && !missing(lib.loc)) {
            pkglist <- paste(sQuote(nopkgs), collapse = ", ")
            msg <- sprintf(ngettext(length(nopkgs), "library %s contains no packages", 
                "libraries %s contain no packages"), pkglist)
            warning(msg, domain = NA)
        }
        y <- list(header = NULL, results = db, footer = NULL)
        class(y) <- "libraryIQR"
        return(y)
    }
    if (logical.return) 
        TRUE
    else invisible(.packages())
}

The library command code executes the command. The library( ) executes an empty command.

Exercise 2

getwd()
'/projects/ddda6a8e-2bca-47f5-b1d6-79b2c48d0e30/Autumn2016/Week1'
setwd("~/Autumn2016/Week1")

Marked in red as it's a string/ path, which has no value.

Exercise 3

x<-3 y<-10 z<-15
x+y+z
28
(y-x)/z
0.466666666666667
x*y*z
450
(x+y+z)^2
784
v<-c(x,y,z)
sum(v)
28

The question states calculate the sum of the vector raised to the power of 4, which can be interperated in two ways. The first method calculates the (sum of the vector) raised to the power of 4, and the second method calculates the sum of (vector raised to the power of 4)

(sum(v))^4
614656
sum(v^4)
60706
sqrt(z-x)
3.46410161513775

Exercise 4

myname <-"Jingyi" email <-"[email protected]" module <-"BMS353" message <- paste(myname,email,module,sep=",") print (message)
[1] "Jingyi,[email protected],BMS353"

Exercise5

seq(1,30,by=2)
  1. 1
  2. 3
  3. 5
  4. 7
  5. 9
  6. 11
  7. 13
  8. 15
  9. 17
  10. 19
  11. 21
  12. 23
  13. 25
  14. 27
  15. 29
seq(2,30,by=2)
  1. 2
  2. 4
  3. 6
  4. 8
  5. 10
  6. 12
  7. 14
  8. 16
  9. 18
  10. 20
  11. 22
  12. 24
  13. 26
  14. 28
  15. 30
a<-seq(1,30,by=2)
b<-seq(2,30,by=2)
length(seq(1,30,by=2))
15
length(seq(2,30,by=2))
15
sum(a)
225
sum(b)
240
sum(seq(1,30))
465

The conclusion is that the sum of the entire sequence of numbers ranging from 1-30 is equal to the total sum of the odd numbers from 1-30 and even numbers from 2-30.

sample(1:100,12,replace=TRUE)
  1. 100
  2. 63
  3. 7
  4. 69
  5. 93
  6. 90
  7. 15
  8. 63
  9. 26
  10. 65
  11. 84
  12. 44

Exercise 6

dept<- "BMS" code<- 353 BMSmodule<- c(dept,as.character(code)) print(BMSmodule)
[1] "BMS" "353"
dept<- "APS" code<- 227 APSmodule<- c(dept,as.character(code)) print(APSmodule)
[1] "APS" "227"
dept<- "MBB" code<- 253 MBBmodule<- c(dept,as.character(code)) print(MBBmodule)
[1] "MBB" "253"
mergevector<- c(BMSmodule,APSmodule,MBBmodule) print(mergevector)
[1] "BMS" "353" "APS" "227" "MBB" "253"
stringsvector<- c("BMS","APS","MBB") print(stringsvector)
[1] "BMS" "APS" "MBB"
x<-c("BMS","APS","MSS") y<-c(353,227,253) z<-c(x,as.character(y)) print(z)
[1] "BMS" "APS" "MSS" "353" "227" "253"
x<-c("BMS","APS","MSS") y<-c(353,227,253) z<- paste(x,y,sep="") print(z)
[1] "BMS353" "APS227" "MSS253"

Exercise 7

Mat1<- matrix(1:20,nrow=4,ncol=5,byrow=TRUE) M
1st2nd3rd4th5th
A 1 2 3 4 5
B 6 7 8 910
C1112131415
D1617181920

In R, matrices are created by column by defult, therefore byrow=TRUE will create the matrix by row.

rownames(M)<-c("A","B","C","D") colnames(M)<-c("1st", "2nd", "3rd","4th","5th") M
1st2nd3rd4th5th
A 1 2 3 4 5
B 6 7 8 910
C1112131415
D1617181920
M=matrix(1:20,nrow=4,ncol=5,byrow=TRUE) M
1 2 3 4 5
6 7 8 910
1112131415
1617181920
M[c(1,2),c(1,2)]
12
67
M[c(1,2),c(1,2,4,5)]
1 2 4 5
6 7 9 10
M[2,]
  1. 6
  2. 7
  3. 8
  4. 9
  5. 10

Exercise 8

Mat2=matrix(c(32,42,18,20,33,38,25,28,26),nrow=3,ncol=3,byrow=TRUE) Mat2
324218
203338
252826
rownames(Mat2)<- c("BMS353","APS227","MBB253") colnames(Mat2)<- c("2013-14","2014-15","2015-16") Mat2
2013-142014-152015-16
BMS353324218
APS227203338
MBB253252826
Mat2["BMS353",]
2013-14
32
2014-15
42
2015-16
18

Exercise 9

Mat3=matrix(sample(1:100,12,replace=TRUE),nrow=3,ncol=4) Mat3
3984658
41508496
7715 140
Mat4=matrix(sample(1:100,12,replace=TRUE),nrow=3,ncol=4) Mat4
32642490
9067 273
28489251
Mat3+Mat4
3516270 148
13111786 169
105 6393 91
Mat4-Mat3
29-34-22 32
49 17-82-23
-49 33 91 11
Mat3-Mat4
-29 34 22-32
-49-17 82 23
49-33-91-11
Mat3 %*% t(Mat4) t(Mat3)%*%Mat4
126921116211978
151681421616172
704810857 5008
5942 66357238 7190
8056103423832 13235
9060 86201364 10323
11616120645264 14268
sqrt(Mat3) sqrt(Mat4)
1.7320519.8994956.7823307.615773
6.4031247.0710689.1651519.797959
8.7749643.8729831.0000006.324555
5.6568548.0000004.8989799.486833
9.4868338.1853531.4142148.544004
5.2915036.9282039.5916637.141428

Exercise 10

myFunction <- function(x) { ux <- x^3-1 return(ux) } test<-myFunction(2) print(test)
[1] 7

2 is the value of the input, and 7 is the value of the output.

x<- c(5,4,3,2,1) print(var(x))
[1] 2.5

The command var(x) computes the variance of x, whcih can be a numeric vector, matrix or data frame.

y<- sum(x) z<- mean(x) n<- length(x) m<- (x-z)^2 a<- sum(m) sd<- (1/(n-1))*a print(sd)
[1] 2.5

y= sum of x z= mean of x n= number of x m= square of x minus mean a= sum of the bars sd= variance

Exercise 11

BMI <- function(h,w){ux<- h/(w^2) return(ux)} test <- BMI(55,1.65) print(test)
[1] 20.20202

w= weight of body in kg h= height of body in m

Exercise 12

Week 1 practical content:

  • Basic operation in R

  • Use of markdown cells

  • Built in help functions in R

  • Changing path and verifying location of workspace

  • Working with vairables and objects, to perform simple calculations

  • Assigning value to object

  • The print command

  • Creating vectors and matrices, as well as their manipulation and calculations.

  • Transform numbers to characters.

  • Rearranging dimensions of matrices

  • Create user defined functions

  • Calculation of variance