根据矢量中的* not *选择R数据帧中的列 [英] Selecting columns in R data frame based on those *not* in a vector
本文介绍了根据矢量中的* not *选择R数据帧中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
df .2 < - df [,c(name1,name2,name3)]
但是可以使用!
或其他工具来选择列出的所有列?
对于背景,我有一个包含很多列向量的数据框,我想避免:
- 输出大部分名字,当我可以删除少数
- 使用更短的
df.2 < - df [,c(1,3,5) ]
因为当我的.csv文件发生变化时,我的代码会因为编号不一样了。我是R的新人,认为我已经学会了不要使用数字向量来改变更大的df。
我试过:
df.2 < - df [,!c(name1,name2,name3 )]
df.2 < - df [,!= c(name1,name2,name3)]
正如我输入的那样,发现这样做是有效的:
df .2 < - df [%]%c(name1,name2,name3)中的名称(df)%]
有没有比最后一个更好的方法?
解决方案
c $ c> grep 是哪个
:
df.2 < - df [, - 其中%c中的(df)%(name1,name2,name3))]
pre>
I'm familiar with being able to extract columns from an R data frame (or matrix) like so:
df.2 <- df[, c("name1", "name2", "name3")]
But can one use a
!
or other tool to select all but those listed columns?For background, I have a data frame with quite a few column vectors and I'd like to avoid:
- Typing out the majority of the names when I could just remove a minority
- Using the much shorter
df.2 <- df[, c(1,3,5)]
because when my .csv file changes, my code goes to heck since the numbering isn't the same anymore. I'm new to R and think I've learned the hard way not to use number vectors for larger df's that might change.
I tried:
df.2 <- df[, !c("name1", "name2", "name3")]
df.2 <- df[, !=c("name1", "name2", "name3")]
And just as I was typing this, found out that this works:
df.2 <- df[, !names(df) %in% c("name1", "name2", "name3")]
Is there a better way than this last one?
解决方案
An alternative to grep
is which
:
df.2 <- df[, -which(names(df) %in% c("name1", "name2", "name3"))]
这篇关于根据矢量中的* not *选择R数据帧中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文