Grep不在R工作

时间:2015-07-03 19:39:24

标签: r

我无法理解为什么我的R中的grep函数不起作用。我认为这与我的检查字和我的关键字列表的数据类型有关。这是我的输出:

forvalues x=1/213 {
use Base_T03.dta, clear
egen trend=fill(1/1491)
drop if trend <7*(`x'-1)+1 | trend > 7*(`x')

gen str variable=""
replace variable="consumption_growth" in 1
replace variable="gov_expo_growth" in 2
replace variable="exports_growth" in 3
replace variable="imports_growth" in 4
replace variable="gdp_growth" in 5
replace variable="population_growth" in 6

egen m1= mean (consumption_growth)
egen m2= mean (gov_expo_growth)
egen m3= mean (exports_growth)
egen m4= mean (imports_growth)
egen m5= mean (gdp_growth)
egen m6= mean (population_growth)

gen Mean = .
replace Mean=m1 in 1
replace Mean=m2 in 2
replace Mean=m3 in 3
replace Mean=m4 in 4
replace Mean=m5 in 5
replace Mean=m6 in 6

drop m*

egen m1= median (consumption_growth)
egen m2= median (gov_expo_growth)
egen m3= median (exports_growth)
egen m4= median (imports_growth)
egen m5= median (gdp_growth)
egen m6= median (population_growth)

gen Median = .
replace Median=m1 in 1
replace Median=m2 in 2
replace Median=m3 in 3
replace Median=m4 in 4
replace Median=m5 in 5
replace Median=m6 in 6

drop m*

egen m1= max (consumption_growth)
egen m2= max (gov_expo_growth)
egen m3= max (exports_growth)
egen m4= max (imports_growth)
egen m5= max (gdp_growth)
egen m6= max (population_growth)

gen Max = .
replace Max=m1 in 1
replace Max=m2 in 2
replace Max=m3 in 3
replace Max=m4 in 4
replace Max=m5 in 5
replace Max=m6 in 6

drop m*

egen m1= min (consumption_growth)
egen m2= min (gov_expo_growth)
egen m3= min (exports_growth)
egen m4= min (imports_growth)
egen m5= min (gdp_growth)
egen m6= min (population_growth)

gen Min = .
replace Min=m1 in 1
replace Min=m2 in 2
replace Min=m3 in 3
replace Min=m4 in 4
replace Min=m5 in 5
replace Min=m6 in 6

drop m*

egen m1= sd (consumption_growth)
egen m2= sd (gov_expo_growth)
egen m3= sd (exports_growth)
egen m4= sd (imports_growth)
egen m5= sd (gdp_growth)
egen m6= sd (population_growth)

gen Desvest = .
replace Desvest=m1 in 1
replace Desvest=m2 in 2
replace Desvest=m3 in 3
replace Desvest=m4 in 4
replace Desvest=m5 in 5
replace Desvest=m6 in 6

drop m* trend
drop if variable==""
drop consumption* gov_expo* exports* imports* gdp* population* year
save Tabla_`x'.dta, replace
}

2 个答案:

答案 0 :(得分:2)

在我看来 delwords 这里实际上是 data.frame 。请试着看看什么是delwords类。它应该是list,而不是data.frame

class(delwords)

另外,我创建了这个示例:

check  = "DESIRE"
delwords = list("INITIAL","DELIVERABL","DEMONSTRAT","DESIR","DESIRE")

grep(check,delwords)

它似乎正常工作:

[1] 5

答案 1 :(得分:1)

正如指出的那样@grubjesic,您发布的delwords输出形式表明

> class(delwords)
[1] "data.frame"

如果是这种情况,则@akrun在评论中提出的解决方案有效:

> grep(check,delwords$delete)
[1] 5

或者,如果您不一定需要使用grep,则可以使用

获得相同的结果
> which(delwords$delete==check)
[1] 5

而且,作为最终测试,您可以尝试:

> delwords[grep(check,delwords$delete),]
[1] DESIRE
Levels: DELIVERABL DEMONSTRAT DESIR DESIRE INITIAL

在这篇文章中,我只扩展了@akrun和@grubjesic的建议。他们应该获得学分。这篇文章的唯一目的是提供一些进一步的说明。