Reputation: 474
I am trying to subset a data frame so that if a column name is present I subset but if not I ignore. For the example I will use mtcars data set. What I am trying to accomplish is if there is a column "vs" subset the first 3 columns and vs. This would be a dateframe named "vsdf".
df <- mtcars
if(colnames(df)=="vs") {
vsdf <- df[,1,2,3,"vs"]
} else {
NULL
}
Any help or guidance would be greatly appreciated.
Upvotes: 0
Views: 1353
Reputation: 70336
There are two problems with your code:
1) using ==
You want to check whether "vs" is part of the columns names, but since you're using ==
it means that you're checking whether the column names (all that are present) are exactly "vs". This will only be true if there's only one column and that is called "vs". Instead you need to use %in%
, as in
if("vs" %in% colnames(d))
{...}
2) the subetting syntax df[,1,2,3,"vs"]
subsetting a data.frame usually follows the syntax
df[i, j]
where i
denotes rows and j
denotes columns. Since you want to subset columnns, you'll do this in j
. What you did is supply much more arguments to [.data.frame
than it takes because you didn't put those values into a vector. The vector can be numeric / integer or a character vector, but not both forms mixed, as you did. Instead you can build the vector like this:
df[, c(names(df)[1:3], "vs")]
Upvotes: 1