If you have a dataframe like this
mydf <- data.frame(firstcol = c(1,2,1), secondcol = c(3,4,5))
Why would
mydf[mydf$firstcol,]
work but
mydf[firstcol,]
wouldn’t?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can do this:
Remember that the column goes second, not first.
In your example, to see what
mydf[mydf$firstcol,]gives you, let’s break it down:So really
mydf[mydf$firstcol,]is the same asSo you are asking for rows 1, 2, and 1. That is, you are asking for your row one to be the same as row 1 of
mydf, your row 2 to be the same as row 2 ofmydfand your row 3 to be the same as row 1 ofmydf; and you are asking for both columns.Another question is why the following doesn’t work:
That is, why do you have to put quotes around the column name when you ask for it like that but not when you do
mydf$firstcol. The answer is just that the operators you are using require different types of arguments. You can look at'$'to see the form x$name and thus the second argument can be a name, which is not quoted. You can then look up?'[', which will actually lead you to the same help page. And there you will find the following, which explains it. Note that a “character” vector needs to have quoted entries (that is how you enter a character vector inR(and many other languages).