简体   繁体   English

在r中使用if…else语句进行子集

[英]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. 对于示例,我将使用mtcars数据集。 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". 我要完成的工作是,如果前三列中有一个列“ vs”子集,而vs.这将是一个名为“ 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 == 1)使用==

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". 您想检查“ vs”是否是列名的一部分,但是由于使用的是==因此这意味着您要检查列名(是否存在)是否完全是“ vs”。 This will only be true if there's only one column and that is called "vs". 仅当只有一列,即“ vs”时,这才是正确的。 Instead you need to use %in% , as in 相反,您需要使用%in% ,如

if("vs" %in% colnames(d)) 
 {...}

2) the subetting syntax df[,1,2,3,"vs"] 2)分词语法df[,1,2,3,"vs"]

subsetting a data.frame usually follows the syntax 子集data.frame通常遵循以下语法

df[i, j] 

where i denotes rows and j denotes columns. 其中i表示行, j表示列。 Since you want to subset columnns, you'll do this in j . 由于要对columnns进行子集化,因此将在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. 您所做的是为[.data.frame提供了更多的参数,因为您没有将这些值放入向量中。 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")]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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