R Programming Week 3 Quiz & Ans

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kidpea_lau/article/details/82758238

Q1:

Take a look at the 'iris' dataset that comes with R. The data can be loaded with the code:

> library(datasets)
> data(iris)

A description of the dataset can be found by running

>?iris

There will be an object called 'iris' in your workspace. In this dataset, what is the mean of 'Sepal.Length' for the species virginicaPlease round your answer to the nearest whole number.(取整数)

(Only enter the numeric result and nothing else.)

ANSWER:

#直接使用mean函数,mean(x),用[]来取特定值
> mean(iris[iris$Species == "virginica",]$Sepal.Length)
[1] 6.588

or:

#或者使用tapply函数,tapply(vector, index, function):
> tapply(iris$Sepal.Length,iris$Species=="virginica",mean)

FALSE  TRUE 
5.471 6.588 
7

Q2

Continuing with the 'iris' dataset from the previous Question, what R code returns a vector of the means of the variables 'Sepal.Length', 'Sepal.Width', 'Petal.Length', and 'Petal.Width'?

  • apply(iris[, 1:4], 1, mean)
  • apply(iris[, 1:4], 2, mean)   ✔   主要是apply功能的运用问题,可以参考前一文章中apply函数的用法:语言实现循环loop的函数解读​​​​​​​
  • apply(iris, 1, mean)
  • colMeans(iris)
  • apply(iris, 2, mean)
  • rowMeans(iris[, 1:4])

Q3

Load the 'mtcars' dataset in R with the following code

> library(datasets)
> data(mtcars)
> ?mtcars

There will be an object names 'mtcars' in your workspace. You can find some information about the dataset by running

How can one calculate the average miles per gallon (mpg) by number of cylinders in the car (cyl)? Select all that apply.

  • sapply(mtcars, cyl, mean)    #未選擇的是正確的 
  • sapply(split(mtcars$mpg, mtcars$cyl), mean)  #正確 
  • mean(mtcars$mpg, mtcars$cyl) #未選擇的是正確的 
  • tapply(mtcars$cyl, mtcars$mpg, mean) #未選擇的是正確的 
  • split(mtcars, mtcars$cyl)  #未選擇的是正確的 
  • lapply(mtcars, mean)  #未選擇的是正確的 
  • with(mtcars, tapply(mpg, cyl, mean))  #正確 
  • apply(mtcars, 2, mean)  #未選擇的是正確的 
  • tapply(mtcars$mpg, mtcars$cyl, mean)  #正確 

(主要是apply功能的运用问题,可以参考前一文章中apply函数的用法:R语言实现循环loop的函数解读



Q4

Continuing with the 'mtcars' dataset from the previous Question, what is the absolute difference between the average horsepower of 4-cylinder cars and the average horsepower of 8-cylinder cars?

(Please round your final answer to the nearest whole number. Only enter the numeric result and nothing else.)(取整函数)

#直接使用mean函数mean(x),然后
> mean(mtcars[mtcars$cyl == "8",]$hp) - mean(mtcars[mtcars$cyl == "4",]$hp)

ANSER:

127

Q5

If you run

> debug(ls)
  • Execution of 'ls' will suspend at the beginning of the function and you will be in the browser. #正確 
  • The 'ls' function will execute as usual.
  • The 'ls' function will return an error
  • You will be prompted to specify at which line of the function you would like to suspend execution and enter the browser.

猜你喜欢

转载自blog.csdn.net/kidpea_lau/article/details/82758238
ans