使用部分列名在数据框中选择多列 [英] Selecting multiple columns in data frame using partial column name
本文介绍了使用部分列名在数据框中选择多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框,DF,列名都包含颜色名称:
I have a data frame, DF, and the column names all contain color names:
red_balloons green_balloons red_balls blue_balls green_hats red_horses yellow_things
我想做的是根据多个颜色名称选择多个列.我可以像这样一次选择一列:
What I would like to do is select multiple columns based on more than one color name. I can select one column at a time like this:
grep("red", colnames(DF))
但我无法弄清楚或找出如何选择多列.我试过这个:
But I cannot figure out or find out how to select multiple columns. I tried this:
grep(c("red", "blue"), colnames(DF))
但收到以下警告:
Warning message:
In grep(c("mean()", "std()"), colnames(L21), value = FALSE) :
argument 'pattern' has length > 1 and only the first element will be used
建议?
推荐答案
您可以使用|"用于 grep 中的或"
You can use "|" for "or" in grep
grep("red|blue", DF, value=T)
# [1] "red_balloons" "red_balls" "blue_balls" "red_horses"
这篇关于使用部分列名在数据框中选择多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文