Saturday, July 18, 2020

Blog 30: Tips and Tricks on List names

List-Tips and Hacks


Introduction

In this Blog we will look at a handy trick which can make life simple while working with lists. Normally, we tend to work with a list without giving proper names to its different elements. However this practise is not ideal and we will look at how exactly we can handle it correclty


Naming different componenets within a list

In the below example, I have created a list with three elements: A, B and 1:6 numbers. As you can see that there are no names given to each elements. We will assign names to each element so that it will be easy to reference

l1<-list("A","B",1:6)
names(l1)
NULL
names(l1)<-paste0("element",1:length(l1))
l1
$element1
[1] "A"

$element2
[1] "B"

$element3
[1] 1 2 3 4 5 6


Assigning proper names when some elements are named and other are not

Lets say that the element A is given a name Name1 while others are not provided any name. In the below example we will see how we can name the other elements appropriately while keeping the name of element A intact

l2<-list(Name1="A","B",1:6)
names(l2)
[1] "Name1" ""      ""     
new_nm<-ifelse(names(l2)=="",paste0("element",1:length(l1)),names(l2))
new_nm
[1] "Name1"    "element2" "element3"


Assigning these names to the list

names(l2)<-new_nm
l2
$Name1
[1] "A"

$element2
[1] "B"

$element3
[1] 1 2 3 4 5 6


Final Comments

We saw how we can use the above code to appropriately structure the list before doing any analysis


Web Scraping Tutorial 2 - Getting the Avg Rating and Reviews Count

Web Scrapping Tutorial 2: Getting Overall rating and number of reviews ...