我数据框中的列名为col_rent,col_oil等
我在下面的数组中有一个单词列表。如果您在其中任何一个前面加上" col _",则会得到一个列名。
> listofwords
[1] "rent"
[2] "pay"
[3] "oil"
[4] "gas"
[5] "food"
我想找到每个列的索引。
我尝试按如下方式grep它,我基本上想要找到col_rent,col_pay,col_oil,col_gas,col_food的列号,而不使用for循环
> grep(paste0("CM_",listofwords),names(dfread))
[1] 359
Warning message:
In grep(paste0("CM_", listofwords), names(dfread)) :
argument 'pattern' has length > 1 and only the first element will be used
然而,正如消息所说,它不允许我grep列表中的每个成员。我该怎么做才能最终得到一个数字列表,每个数字都显示数据框中出现这些列的列名。
答案 0 :(得分:0)
也许你应该对你的操作进行矢量化:
sapply(paste0("CM_",listofwords), function( element ) {
grep(element,names(dfread))
})
这对我有用:
> listofwords <-c( "rent",
+ "pay",
+ "oil",
+ "gas",
+ "food")
> as.array(listofwords)
[1] "rent" "pay" "oil" "gas" "food"
> dfread <- data.frame( CM_pay = 0,
+ CM_rent = 1,
+ CM_aaa1 = 3,
+ CM_oil = 2,
+ CM_aaa2 = 7,
+ CM_gas = 8,
+ CM_food = 9
+ )
> colnames(dfread)
[1] "CM_pay" "CM_rent" "CM_aaa1" "CM_oil" "CM_aaa2" "CM_gas" "CM_food"
> sapply(paste0("CM_",listofwords), function( element ) {
+ grep(element,names(dfread))
+ })
CM_rent CM_pay CM_oil CM_gas CM_food
2 1 4 6 7