如何选择名称中包含特定字符串的R数据框中的变量? [英] How do I select variables in an R dataframe whose names contain a particular string?
本文介绍了如何选择名称中包含特定字符串的R数据框中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我会如何选择:
1)名称以b或B开头的变量(即case-不敏感)
或
2)变量,其名称包含一个3
df < - data.frame (a1 = factor(c(Hi,Med,Hi,Low),
levels = c(Low,Med,Hi),ordered = TRUE)
a2 = c(A,D,A,C)a3 = c(8,3,9,9) 1,2,4),b2 = c(5,4,3,2),b3 = c(3,4,3,4),
B1 = c(3,6,4,4))
解决方案
如果您只需要变量名称:
grep(^ [Bb],names(df),value = TRUE)
grep(3 ,名称(df),值= TRUE)
如果您想要选择这些列,
df [,grep(^ [Bb],names(df),value = TRUE)]
df [,grep(^ [bb],names(df))]
第一次使用按名称选择,第二个使用选择由一组列号组成。
Two examples would be very helpful for me.
How would I select: 1) variables whose names start with b or B (i.e. case-insensitive) or 2) variables whose names contain a 3
df <- data.frame(a1 = factor(c("Hi", "Med", "Hi", "Low"),
levels = c("Low", "Med", "Hi"), ordered = TRUE),
a2 = c("A", "D", "A", "C"), a3 = c(8, 3, 9, 9),
b1 = c(1, 1, 1, 2), b2 = c( 5, 4, 3,2), b3 = c(3, 4, 3, 4),
B1 = c(3, 6, 4, 4))
解决方案
If you just want the variable names:
grep("^[Bb]", names(df), value=TRUE)
grep("3", names(df), value=TRUE)
If you are wanting to select those columns, then either
df[,grep("^[Bb]", names(df), value=TRUE)]
df[,grep("^[Bb]", names(df))]
The first uses selecting by name, the second uses selecting by a set of column numbers.
这篇关于如何选择名称中包含特定字符串的R数据框中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文