The post How to copy a list in Python appeared first on We provide R, Python, Statistics Online-Learning Course.
]]>The mechanism for copying a list in Python appears somewhat different than in other programming languages. If you just use equal symbol to assign an existing list to a new one, both objects refer to the same one which is stored in the computers memory. Say we have a list for favorite languages and create a new one using equal symbol.
fav_prog = ['python','C','C++','Java']
fav_prog_2 = fav_prog
#display the new list
fav_prog_2
#output
['python', 'C', 'C++', 'Java']
#now we add one element into one of the two lists
fav_prog.append('Ruby')
#show first list
fav_prog
#output
['python', 'C', 'C++', 'Java', 'Ruby']
#show the second list
fav_prog_2
#output
Out[4]: ['python', 'C', 'C++', 'Java', 'Ruby']
It is clear that both lists have new element added, even we have just append element to only one of them. So if you want to avoid such unexpected result, we have to use slice symbol , “:” in Python to copy list.
#create the first list
fav_prog = ['python','C','C++','Java']
#copy a list using colon symbol
fav_prog_2 = fav_prog[:]
#show second list
fav_prog_2
#output
['python', 'C', 'C++', 'Java']
#now we add one element to the first list
fav_prog.append('Ruby')
#show again the first list
fav_prog
#output
['python', 'C', 'C++', 'Java', 'Ruby']
#show again the second list
fav_prog_2
#output
['python', 'C', 'C++', 'Java']
#we add one element to the second list
fav_prog_2.append("PHP")
#show again the second list
fav_prog_2
#output
['python', 'C', 'C++', 'Java', 'PHP']
#show the first list again
fav_prog
#output
['python', 'C', 'C++', 'Java', 'Ruby']
It is ok that two lists now refer to two individual objects, which is what we want to see.
The post How to copy a list in Python appeared first on We provide R, Python, Statistics Online-Learning Course.
]]>The post Create, index and modify lists in R appeared first on We provide R, Python, Statistics Online-Learning Course.
]]>List is a type of data objects in R. It can store different types of data objects into one object. You can combine scalars, vectors, matrices, data frames, and even lists into a single list object. A list can be created using list() function in R. The code below shows a simple example to create a list which contains information from scalar, vector and matrix.
#create a scalar a, vector b, numeric matrix c
#and character vector d
a <- "My First List"
b <- c(32, 33, 36)
c <- matrix(1:10, nrow = 2)
d <- c("wang", "zhang", "li")
#create a list mynewlist, with information from
#a,b,c,d. and set name for first two elements in the list
mynewlist <- list(title = a, sum =b, c, d)
#show a list
> mynewlist
$title
[1] "My First List"
$sum
[1] 32 33 36
[[3]]
[,1] [,2] [,3] [,4] [,5]
[1,] 1 3 5 7 9
[2,] 2 4 6 8 10
[[4]]
[1] "wang" "zhang" "li"
It is shown that there are now four elements in the list ‘mynewlist’. When the elements in the list have no name assigned, R will use double bracket [[ ]] to index those elements. Actually double brackets as well as the dollar symbol can be used to index and return the elements of the list, which is shown in the follow code example for family member creation.
#index and return the second element of the list
mynewlist[[2]]
[1] 32 33 36
#index and return the contents of the element assigned with name 'sum'
> mynewlist[["sum"]]
[1] 32 33 36
#index and return the contents of the element assigned with name 'sum'
> mynewlist$sum
[1] 32 33 36
Of course you can assignment each element with corresponding name when creating a list.
# vector with names
name1=c("Wilson","Dudu","Maomao","Miaomiao")
# vector age
age1=c(32,20,22,10)
address vector
address1=c("Aukra","Molde","Molde","Aukra")
# pass these vectors as inputs to the list
familymember1=list(name1= name1,age1= age1,address1= address1)
#show the list contents
print(familymember1)
$name1
[1] "Wilson" "Dudu" "Maomao" "Miaomiao"
$age1
[1] 32 20 22 10
$address1
[1] "Aukra" "Molde" "Molde" "Aukra"
> familymember1
$name1
[1] "Wilson" "Dudu" "Maomao" "Miaomiao"
$age1
[1] 32 20 22 10
$address1
[1] "Aukra" "Molde" "Molde" "Aukra"
You can append a element to an existing list.
#a new vector for name
name2=c("Mico","Mia")
#append name2 to an existing list
familymember1=list(familymember1,name2)
#show list again
familymember1
[[1]]
[[1]]$name1
[1] "Wilson" "Dudu" "Maomao" "Miaomiao"
[[1]]$age1
[1] 32 20 22 10
[[1]]$address1
[1] "Aukra" "Molde" "Molde" "Aukra"
[[2]]
[1] "Mico" "Mia"
You can see, when new element is assigned into an existing list, R will add extra double brackets to the elements in the list.
The contents of a list can be simply modified by using same indexing method as before, with the new value assigned.
#index and return first value of the element 'address1'
familymember1[[1]]$address1[1]
[1] "Aukra"
#assign new value to first value of the element 'address1'
familymember1[[1]]$address1[1]<-'Oslo'
#show list again
familymember1
[[1]]
[[1]]$name1
[1] "Wilson" "Dudu" "Maomao" "Miaomiao"
[[1]]$age1
[1] 32 20 22 10
[[1]]$address1
[1] "Oslo" "Molde" "Molde" "Aukra"
[[2]]
[1] "Mico" "Mia"
For more illustrative knowledge of R, You can watch tutorial videos on our YouTube channel.
The post Create, index and modify lists in R appeared first on We provide R, Python, Statistics Online-Learning Course.
]]>The post Some useful functions for working with objects in R appeared first on We provide R, Python, Statistics Online-Learning Course.
]]>In this post, we will introduce and provide several useful and important functions in R. Most of them are fairly basic, and frequently used in data analysis with R programming.
length() – get the length of an object
#to show first three observations of a data frame 'grade'
head(grade,3)
StudentID Fullname Race Gender Country Age Math Physics
1 1 James Zhang A Male US 23 73 70
2 2 Wilson Li E Female UK 26 95 76
3 3 Richard Nuan Ye A Male UK 35 77 83
Chemistry Date
1 87 10/31/2008
2 83 3/16/2008
3 92 5/22/2008
#length of data frame 'grade'
length(grade)
[1] 10
#to create a vector
test<-grade$Age
#length of a vector
length(test)
[1] 20
dim() – to show the dimension of an object
#dimension of a data frame
dim(grade)
[1] 20 10
str() – to show structure of a data frame
str(grade)
'data.frame': 20 obs. of 10 variables:
$ StudentID: chr "1" "2" "3" "4" ...
$ Fullname : chr "James Zhang" "Wilson Li" "Richard Nuan Ye" "Mary Deng" ...
$ Race : chr "A" "E" "A" "E" ...
$ Gender : chr "Male" "Female" "Male" "Female" ...
$ Country : chr "US" "UK" "UK" "US" ...
$ Age : num 23 26 35 21 19 43 37 28 19 25 ...
$ Math : num 73 95 77 60 77 79 87 95 73 66 ...
$ Physics : num 70 76 83 99 89 64 99 87 92 93 ...
$ Chemistry: num 87 83 92 84 93 83 67 93 84 65 ...
$ Date : chr "10/31/2008" "3/16/2008" "5/22/2008" "1/24/2009" ...
class() – to show class type of an object
#class of a data frame
class(grade)
[1] "data.frame"
#class of an vector
class(test)
[1] "numeric"
mode() – to show the mode(data storage type) of an object
#mode of a data frame
mode(grade)
[1] "list"
#mode of a vector
mode(test)
[1] "numeric"
names() – to show the names of an object
#names of columns of a data frame
names(grade)
[1] "StudentID" "Fullname" "Race" "Gender" "Country"
[6] "Age" "Math" "Physics" "Chemistry" "Date"
c() – Combine extra elements to a vector
test2<-c(test, 20, 20)
test2
[1] 23 26 35 21 19 43 37 28 19 25 42 32 27 35 21 29 36 39 24 25 20
[22] 20
cbind() – Combines data frames across columns
#to create a data frame of 3 columns
gradepart<-grade[,c(7:9)]
names(gradepart)<-c("v1","v2","v3")
#combine two data frames
test3<-cbind(grade,gradepart )
#show first 3 observations of the combined data frame
head(test3,3)
StudentID Fullname Race Gender Country Age Math Physics
1 1 James Zhang A Male US 23 73 70
2 2 Wilson Li E Female UK 26 95 76
3 3 Richard Nuan Ye A Male UK 35 77 83
Chemistry Date v1 v2 v3
1 87 10/31/2008 73 70 87
2 83 3/16/2008 95 76 83
3 92 5/22/2008 77 83 92
>
rbind() – Combines data frames across rows
#to create a new data frame of 10 rows
test4<-grade[1:10,]
#combine two data frame along rows
test5<-rbind(grade, test4)
#show first 15 observations of the combined data frame
head(test5,15)
StudentID Fullname Race Gender Country Age Math Physics
1 1 James Zhang A Male US 23 73 70
2 2 Wilson Li E Female UK 26 95 76
3 3 Richard Nuan Ye A Male UK 35 77 83
4 4 Mary Deng E Female US 21 60 99
5 5 Jason Wilson A Male UK 19 77 89
6 6 Jennifer Hopkin A Female UK 43 79 64
7 7 Kari Gjendem E Female US 37 87 99
8 8 Wenche Dale E Female US 28 95 87
9 9 Jane Larsen A Female US 19 73 92
10 10 Steinar Hansen A Male US 25 66 93
11 11 Michael Chen A Male UK 42 83 90
12 12 Josef Curton E Male US 32 71 63
13 13 Jennifer Jones E Male US 27 79 76
14 14 Gary Grant E Female UK 35 90 78
15 15 Phil Yao A Male UK 21 69 69
Chemistry Date
1 87 10/31/2008
2 83 3/16/2008
3 92 5/22/2008
4 84 1/24/2009
5 93 7/30/2009
6 83 4/5/2009
7 67 11/24/2008
8 93 10/2/2008
9 84 6/5/2009
10 65 8/1/2008
11 77 10/24/2008
12 96 11/8/2009
13 82 10/29/2008
14 92 10/24/2008
15 83 10/15/2008
seq() – to create a sequence of numbers into a vector
#generate a vector from 1 to 10
seq(1,10)
[1] 1 2 3 4 5 6 7 8 9 10
#generate a vector of 5 numbers between 1 and 10, gap 2
seq(1,10,2)
[1] 1 3 5 7 9
rep() – generate a sequence of number with repetition
#generate a vector 1,1,1,1,1
rep(1,5)
[1] 1 1 1 1 1
#generate a vector 1,2,1,2,1,2,1,2,1,2
rep(c(1,2),5)
[1] 1 2 1 2 1 2 1 2 1 2
You can also watch R tutorial videos on our YouTube channel.
The post Some useful functions for working with objects in R appeared first on We provide R, Python, Statistics Online-Learning Course.
]]>The post Working with Python classes and instances appeared first on We provide R, Python, Statistics Online-Learning Course.
]]>Python uses class for object-oriented programming. A class represents the general behavior or information that the programmer or data analyst focuses on. When a class is created, particular objects belonging to this class can be created. This process is called instantiation. Class contains attributes, methods, or functions for general purpose. Attributes for instances can be modified by directly assigning new values, or by using methods defined in a class.
In the following code example, we first define a class for automobile. The class Auto contains four attributes: producer, type, year, and the distance(km) it has been driven. There are four methods (functions) defined for this class:
show_info() – to show basic information of the automobile.
show_km() – to show distance in kilometers the car has been driven.
update_km – to update the driving distance with the input new value.
increment_km() – to update the driving distance by add the increment to the current distance.
class Auto():
"""A class for automobile."""
def __init__(self, producer, type, year):
"""Initialize attributes to describe a car."""
self.producer = producer
self.type = type
self.year = year
self.km = 0
def show_info(self):
"""Show information of the car"""
full_info = str(self.year) + ' ' + self.producer + '
' + self.type
return full_info.title()
def show_km(self):
"""Show the kilometer of the car."""
print("The automobil has driven " + str(self.km) + "
now.")
def update_km(self, new_km):
"""
Update the distance of the car.
"""
if new_km >= self.km:
self.km = new_km
else:
print("The updated value should be larger than
the current!")
def increment_km(self, increment):
"""Add the given kilometer to the current"""
self.km += increment
After the class Auto definition is completed, object instances can be created by calling the class. In the following code example, an instance of Auto class, my_volvo is created. Then the driving distance is updated by different methods and shown.
#create an automobil instance from the class Auto
my_volvo = Auto('Volvo', 'V60', 2012)
#show basic information of my_volvo
print(my_volvo.show_info())
# 2012 Volvo V60
#show driving distance of the car
my_volvo.show_km()
# The automobil has driven 0 now.
#update the driving distance by method updata_km()
my_volvo.update_km(56700)
#show driving distance of the car
my_volvo.show_km()
#The automobil has driven 56700 now.
#make increment of the driving distance by method #increment_km()
my_volvo.increment_km(300)
#show driving distance of the car
my_volvo.show_km()
#The automobil has driven 57000 now.
#update driving distance by directly assigning a new value
#to attribute 'km'
my_volvo.km = 100000
#show driving distance of the car
my_volvo.show_km()
The automobil has driven 100000 now.
You can also watch video of Python full course training from our YouTube channel.
The post Working with Python classes and instances appeared first on We provide R, Python, Statistics Online-Learning Course.
]]>