Section 5.2 Creating Data Vectors in R
Now letβs figure out how to get these rows and columns into R. One thing you will quickly learn about R is that there is almost always more than one way to accomplish a goal. Sometimes the quickest or most efficient way is not the easiest to understand. In this case we will build each column one by one and then join them together into a single data frame. This is a bit labor intensive, and not the usual way that we would work with a data set, but it is easy to understand. First, run this command to make the column of names:
One thing you might notice is that every name is placed within double quotes. This is how you signal to R that you want it to treat something as a string of characters rather than the name of a storage location. If we had asked R to use Dad instead of "Dad" it would have looked for a storage location (a data object) named Dad. Another thing to notice is that the commas separating the different values are outside of the double quotes. If you were writing a regular sentence this is not how things would look, but for computer programming the comma can only do its job of separating the different values if it is not included inside the quotes. Once you have typed the line above, remember that you can check the contents of myFamName by typing it on the next command line:
myFamName
The output should look like this:
[1] "Dad" "Mom" "Sis" "Bro" "Dog"
Next, you can create a vector of the ages of the family members, like this:
Note that this is exactly the same command we used in the last chapter, so if you have kept R running between then and now you would not even have to retype this command because myFamAge would still be there. Actually, if you closed R since working the examples from the last chapter you will have been prompted to "save the workspace" and if you did so, then R restored all of the data objects you were using in the last session. You can always check by typing myFamAge on a blank command line. The output should look like this:
[1] 43 42 12 8 5
Hey, now you have used the
c()
function and the assignment arrow to make myFamName and myFamAge. If you look at the data table earlier in the chapter you should be able to figure out the commands for creating myFamGend and myFamWeight. In case you run into trouble, these commands also appear on the next page, but you should try to figure them out for yourself before you turn the page. In each case after you type the command to create the new data object, you should also type the name of the data object at the command line to make sure that it looks the way it should. Four variables, each one with five values in it. Two of the variables are character data and two of the variables are integer data. Here are those two extra commands in case you need them:
myFamGend <- c("Male","Female","Female","Male","Female")
myFamWeight <- c(188,136,83,61,44)
You have attempted of activities on this page.