How to Convert an R List Element to a Vector

Techwalla may earn compensation through affiliate links in this story. Learn more about our affiliate and product review process here.

R, a statistical software package, provides the user with a wide array of data types. One such data type, the list, is convenient in that it allows the organization of data. However, users cannot perform numerical computations on lists, even if the lists contain only numbers. The key to getting around this obstacle and changing an element in the list to a vector is to convert the list to a vector and grab the element from the vector, which is a simple process.

Advertisement

Step 1

Display the list and count the position in the list where the element is located. In R, type the name of the list and hit "Enter" to display the list. For example, if you have a list that is stored as "list1," just type "list1". The list, for example, a = 12, b = 22, c = 32, will appear on the screen. If you want the element corresponding to c, you want the third element.

Advertisement

Video of the Day

Step 2

Convert the list to a vector through the "unlist" command and store it. Type in "yourvector <- unlist(yourlist)" where "yourlist" is the name of your list. In the previous example, you would type "yourvector <- unlist(list1)".

Step 3

Tell R which element in the vector you want and store it as an element. Type "yourelement <- yourvector[number]" where "number" is the position of the element you want. In the example, you want the third element, so you would type "yourelement <- yourvector[3]". This element is now in vector form.

Advertisement

Video of the Day

Advertisement

Advertisement

Report an Issue

screenshot of the current page

Screenshot loading...