![]() We’re interrupting your regular program for a newsflash: stop looking around on internet! R will help you find the perfect (or less perfect if you’re so inclined) match for you! Do you want to find a particular value (or set of) in a vector or data frame? Do you simply want to know if a vector shares some of your values? Look no further, R is here! – Multiply values in ‘vecB’ by the value in the 5th row of the 3rd colum of ‘ex.data’ – Create a vector ‘SupVecA’ only containing the values of ‘vecA’ higher than the ‘vecA’ ‘s median Oh… What is this last line? Oh, right, we had a missing value in our original dataset, leading to a corresponding missing value in our test, leading to a missing value in our match, leading to NAs in our final output… Can you remove this last row? Here’s in one way to do it: best_shirts hue perfectness 1 salmon 9 2 orange 7 Let’s select the rows in our data frame that have values in the “awesomeness” column that match this test: best_shirts=shirts best_shirts hue perfectness 1 salmon 9 2 orange 7 NA NA We just figured out which elements in the column “awesomeness” are higher than 6. Want to know which Ryan Reynolds’ shirts are an awesomeness higher than 6? Let’s get them: test_shirts 6 We can now use that to select them: vec 2 3 10 ![]() We see here that the first 3 values answer our test in a positive way, while the 2 last don’t. We can not only extract those elements, but also modify them if we want: color "salmon2" color0 TRUE TRUE TRUE FALSE FALSE Heck, we can even select a full column by leaving the row dimension empty: shirts salmon orange pink powderblue salmon2 peach puff Levels: orange peach puff pink powderblue salmon salmon2 Or the value contained at the intersection of the 3rd row and the 2nd column of a data frame or matrix: shirts 4 For example, if we want the 5th value in a vector: color "salmon2" ![]() The easiest way to select a subset in most R object is to indicate the index (or indices) of the value(s) we want to access between square brackets “ “. The commands might vary slightly depending on the type of object you are working with, but the general idea stays the same: you can access part of an object by its name (if it has one, like a column name) or its index. You can access any individual value or set of values in a R object, as long as you know how to get there. Let’s now see what is available in R to realize those actions. We might also want to extract a couple of columns or rows from a matrix, or simply add a column to an existing data frame. We might for example be interested only in the 5th value of a vector, or would like to perform operations on a specific column of a dataframe. It is easy in R to access only a part of an object. How to access a particular part of your dataset, extract or merge data?
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |