简体   繁体   中英

Subsetting with an if…else statement in r

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.

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")]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM