R语言从基础入门到提高(七)LIST (列表)

13 篇文章 0 订阅
11 篇文章 0 订阅

第1程序:

Lists,why would you need them?

100xp

Congratulations! At this point in thecourse you are already familiar with:

Vectors(向量) (one dimensional array(一维数组)): can hold numeric, character or logical values. The elements in avector all have the same data type.

Matrices (矩阵)(two dimensional array(二维数组)): can hold numeric, characteror logical values. The elements in a matrix all have the same data type.

Data frames(数据对象) (two-dimensional objects(二维对象)): can hold numeric, character or logical values. Within a columnall elements have the same data type, but different columns can be of differentdata type.

Pretty sweet for an R newbie, right? ;-)

要求:

Click 'Submit Answer' to start learningeverything about lists!

好吧,注重概念的理解!!! 解释了一下,为什么要用list数据类型。

第2程序:

Lists,why would you need them? (2)

100xp

A list in R is similar to yourto-do list at work or school: the different items on that list most likelydiffer in length, characteristic, type of activity that has to do be done, ...

A list in R allows you to gather(收集) a variety of(各种各样的) objects under one name (thatis, the name of the list) in an ordered way. These objects can be matrices,vectors, data frames, even other lists, etc. It is not even required that theseobjects are related to each other in any way.

You could say that a list is some kindsuper data type: you can store practically any piece of information in it!

超级类型,可以包含所有类型包括对象及超级类型自己!!!

要求:

Click 'Submit Answer' to start the firstexercise on lists.

又介绍了一下,超级类型,可见这种类型的重要性!!!

第3程序:

Creatinga list

100xp

Let us create our first list! To constructa list you use the function list():

my_list <- list(comp1, comp2 ...)

The arguments to the list function are thelist components(组件).Remember, these components can be matrices, vectors, other lists, ...

使用list( ) 内置函数进行list创建

 

要求:

Construct a list, named my_list, thatcontains thevariables my_vector, my_matrix and my_df as listcomponents.

 

源程序:

 

# Vectorwith numerics from 1 up to 10
my_vector<- 1:10 
 
# Matrixwith numerics from 1 up to 9
my_matrix<- matrix(1:9, ncol = 3)
 
# First 10elements of the built-in data frame mtcars
my_df <-mtcars[1:10,]
 
# Constructlist with these different elements:
my_list<- list(my_vector, my_matrix, my_df)
console:
> #Vector with numerics from 1 up to 10
>my_vector <- 1:10 
> 
> #Matrix with numerics from 1 up to 9
>my_matrix <- matrix(1:9, ncol = 3)
> 
> # First10 elements of the built-in data frame mtcars
> my_df<- mtcars[1:10,]
> 
> #Construct list with these different elements:
> my_list<- list(my_vector, my_matrix, my_df)
> #Vector with numerics from 1 up to 10
>my_vector <- 1:10 
> 
> #Matrix with numerics from 1 up to 9
>my_matrix <- matrix(1:9, ncol = 3)
> 
> # First10 elements of the built-in data frame mtcars
> my_df<- mtcars[1:10,]
> 
> #Construct list with these different elements:
> my_list<- list(my_vector, my_matrix, my_df)
> my_list
[[1]]
 [1] 1  2  3  4  5  6  7  8  9 10
 
[[2]]
    [,1] [,2] [,3]
[1,]   1    4    7
[2,]   2    5    8
[3,]   3    6    9
 
[[3]]
                  mpg cyl disp  hp drat    wt  qsec vs am gear carb
MazdaRX4         21.0   6 160.0 110 3.90 2.62016.46  0  1    4    4
Mazda RX4Wag     21.0   6 160.0 110 3.90 2.875 17.02 0  1    4    4
Datsun710        22.8   4 108.0  93 3.85 2.32018.61  1  1    4    1
Hornet 4Drive    21.4   6 258.0 110 3.08 3.215 19.44  1 0    3    1
HornetSportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0   3    2
Valiant          18.1   6 225.0 105 2.76 3.46020.22  1  0    3    1
Duster360        14.3   8 360.0 245 3.21 3.57015.84  0  0    3    4
Merc240D         24.4   4 146.7  62 3.693.190 20.00  1  0    4    2
Merc230          22.8   4 140.8  95 3.923.150 22.90  1  0    4    2
Merc280          19.2   6 167.6 123 3.92 3.44018.30  1  0    4    4


 

仔细观察一下这三个变量,依次是:向量,矩阵,框架

 

第4程序:

Creatinga named list

100xp

Well done, you're on a roll!

Just like on your to-do list(待完成事件列表), you want to avoid notknowing or remembering what the components(组件) of your list stand for. That is why you should give names to them:

my_list <- list(name1 = your_comp1,

                name2 = your_comp2)

This creates a list with components thatare named name1, name2, and so on. If you want to name your listsafter you've created them, you can use the names() function as you didwith vectors. The following commands are fully equivalent to the assignmentabove:

my_list <- list(your_comp1, your_comp2)
names(my_list) <- c("name1", "name2")

 

#mark#重点理解 

names( ) 也是内置的函数,可以直接使用,给list进行改名;之前就利用names() 函数给向量进行改名的;

 

要求:

Change the code of the previous exercise(see editor) by adding names to the components. Use for my_vector thename vec, for my_matrix the name matandfor my_df the name df.

Print out my_list so you caninspect the output.

 

就是一个改名任务!!

源程序:

 

# Vectorwith numerics from 1 up to 10
my_vector<- 1:10 
 
# Matrixwith numerics from 1 up to 9
my_matrix<- matrix(1:9, ncol = 3)
 
# First 10elements of the built-in data frame mtcars
my_df <-mtcars[1:10,]
 
# Adaptlist() call to give the components names
my_list<- list(my_vector, my_matrix, my_df)
 
# Print outmy_list
names(my_list)<- c("vec", "mat", "df")
my_list
console:
> #Vector with numerics from 1 up to 10
>my_vector <- 1:10 
> 
> # Matrixwith numerics from 1 up to 9
>my_matrix <- matrix(1:9, ncol = 3)
> 
> # First10 elements of the built-in data frame mtcars
> my_df<- mtcars[1:10,]
> 
> # Adaptlist() call to give the components names
> my_list<- list(my_vector, my_matrix, my_df)
> 
> # Printout my_list
>names(my_list) <- c("vec", "mat", "df")
> my_list
$vec
 [1] 1  2  3  4  5  6  7  8  9 10
 
$mat
    [,1] [,2] [,3]
[1,]   1    4    7
[2,]   2    5    8
[3,]   3    6    9
 
$df
                  mpg cyl disp  hp drat    wt  qsec vs am gear carb
MazdaRX4         21.0   6 160.0 110 3.90 2.62016.46  0  1    4    4
Mazda RX4Wag     21.0   6 160.0 110 3.90 2.875 17.02 0  1    4    4
Datsun710        22.8   4 108.0  93 3.85 2.32018.61  1  1    4    1
Hornet 4Drive    21.4   6 258.0 110 3.08 3.215 19.44  1 0    3    1
HornetSportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0   3    2
Valiant          18.1   6 225.0 105 2.76 3.46020.22  1  0    3    1
Duster360        14.3   8 360.0 245 3.21 3.57015.84  0  0    3    4
Merc240D         24.4   4 146.7  62 3.693.190 20.00  1  0    4    2
Merc230          22.8   4 140.8  95 3.923.150 22.90  1  0    4    2
Merc280          19.2   6 167.6 123 3.92 3.44018.30  1  0    4    4


 

 

第5程序:

Creatinga named list (2)

100xp

Being a huge movie fan(铁粉) (remember your job atLucasFilms), you decide to start storing information on good movies with thehelp of lists.

Start by creating a list for the movie"The Shining". We have already created thevariables mov, act and rev in your R workspace. Feelfree to check them out in the console.

 

要求:

Complete the code on the right tocreate shining_list; it contains three elements:

moviename: a character string with themovie title (stored in mov)

actors: a vector with the main actors'names (stored in act)

reviews: a data frame that contains somereviews (stored in rev)

Do not forget to name the list components(组件) accordingly (names aremoviename, actors and reviews).

源程序:

 

# Thevariables mov, act and rev are available
 
# Finish thecode to build shining_list
shining_list<- list(moviename = mov, actors = act, reviews = rev)
shining_list
console:
> # Thevariables mov, act and rev are available
> 
> #Finish the code to build shining_list
>shining_list <- list(moviename = mov, actors = act, reviews = rev)
>shining_list
$moviename
[1]"The Shining"
 
$actors
[1]"Jack Nicholson"   "Shelley Duvall"  "Danny Lloyd"      "Scatman Crothers"
[5]"Barry Nelson"    
 
$reviews
 scores sources                                            comments
1   4.5   IMDb1                    Best Horror Film I Have Ever Seen
2   4.0   IMDb2 A truly brilliant and scary film from StanleyKubrick
3   5.0   IMDb3                A masterpiece of psychological horror


 

第6程序:

Selectingelements from a list

100xp

Your list will often be built out ofnumerous(众多的) elementsand components(组件).Therefore, getting a single (单个)element, multiple(多个) elements, or a component out of it is not always straightforward(通俗).

One way to select a component is using thenumbered position(下标) of thatcomponent. For example, to "grab"(抓取) the first component of shining_list you type

shining_list[[1]]

A quick way to check this out is typing itin the console. Important to remember: to select elements from vectors, you usesingle square brackets(用单个方括号): [ ]. Don't mix them up!

切记不要混淆!

#mark#重点理解

You can also refer to the names of thecomponents, with[[ ]] or with the $ sign. Both will select thedata frame representing the reviews:

#mark#重点理解

 

也可以通过直接点出名字, 用[[ ]]  或 $

 shining_list[["reviews"]]

shining_list$reviews

Besides selecting components, you oftenneed to select specific elements out of these components. For example,with shining_list[[2]][1] you select from the secondcomponent, actors (shining_list[[2]]), the first element ([1]). Whenyou type this in the console, you will see the answer is Jack Nicholson.

要求:

Select from shining_list thevector representing the actors. Simply print out this vector.

Select from shining_list thesecond element in the vector representing the actors. Do a printout likebefore.

源程序:

 

#shining_list is already pre-loaded in the workspace
 
# Print outthe vector representing the actors
shining_list[[2]]
# 这个地方说的很明确,是想要打印,向量提到的所有演员!
# Print thesecond element of the vector representing the actors
# 这个地方是显示,向量里提的到所有演员里的第二个!!
shining_list[[2]][2]
 
console:
> #shining_list is already pre-loaded in the workspace
> 
> # Printout the vector representing the actors
>shining_list[[2]]
[1]"Jack Nicholson"   "Shelley Duvall"  "Danny Lloyd"      "Scatman Crothers"
[5]"Barry Nelson"    
> 
> # Printthe second element of the vector representing the actors
>shining_list[[2]][2]
[1]"Shelley Duvall"


 

 

第7程序:

Addingmore movie information to the list

100xp

Being proud of your first list, you sharedit with the members of your movie hobby club. However, one of the seniormembers, a guy named M. McDowell, noted that you forgot to add the release(发行) year. Given your ambitions tobecome next year's president of the club, you decide to add this information tothe list.

To conveniently(方便) add elements to lists you canuse the c() function, that you also used to build vectors:

ext_list <- c(my_list , my_val)

This will simply extend(拓展) the originallist, my_list, with the component my_val. This component getsappended to the end of the list. If you want to give the new list item a name,you just add the name as you did before:

ext_list <- c(my_list, my_name = my_val)

 

要求:

Complete the code below such that an itemnamed year is added to(添加到) the shining_list with the value 1980. Assign the resultto shining_list_full.

Finally, have a look at the structureof shining_list_full with the str()function.

#mark#重点理解 str( )

源程序:

 

#shining_list, the list containing movie name, actors and reviews, is pre-loadedin the workspace
 
# We forgotsomething; add the year to shining_list
shining_list_full<- c(shining_list, year = 1980)
 
# Have alook at shining_list_full
str(shining_list_full)
console:
> #shining_list, the list containing movie name, actors and reviews, is pre-loadedin the workspace
> 
> # Weforgot something; add the year to shining_list
>shining_list_full <- c(shining_list, year = 1980)
> 
> # Havea look at shining_list_full
>str(shining_list_full)
List of 4
 $moviename: chr "The Shining"
 $actors   : chr [1:5] "Jack Nicholson" "ShelleyDuvall" "Danny Lloyd" "Scatman Crothers" ...
 $reviews  :'data.frame':    3 obs. of  3 variables:
  ..$scores  : num [1:3] 4.5 4 5
  ..$sources : Factor w/ 3 levels "IMDb1","IMDb2",..: 1 2 3
  ..$comments: Factor w/ 3 levels "A masterpiece of psychologicalhorror",..: 3 2 1
 $year     : num 1980


 

 

接下来,应该先巩固,基础打牢,之后再进行能力提高篇!!!


 

 

 

 

 

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值