2012-10-12 47 views
1

我有一个数据集,看起来像这样:如何在R中对变量名称进行子集化?

head(data) 
           country  fixef 
1    as.factor(country.x)Albania -0.4446439 
2    as.factor(country.x)Algeria -0.3400060 
3    as.factor(country.x)Andorra -1.0455948 
4    as.factor(country.x)Angola 0.7477114 
5 as.factor(country.x)Antigua and Barbuda -0.1996655 
6   as.factor(country.x)Argentina -0.3404206 

如何删除(在读)一切除了国家的名字,所以它看起来像这样:

head(data) 
        country  fixef 
1     Albania -0.4446439 
2     Algeria -0.3400060 
3     Andorra -1.0455948 
4     Angola 0.7477114 
5  Antigua and Barbuda -0.1996655 
6     Argentina -0.3404206 

谢谢,

安东尼奥佩德罗。

回答

6

我同意几分钟前发布的答案(但似乎已被撤回),最好不要在第一时间创建该问题!但是如果你想纠正你已经有的东西,看看?gsub并尝试类似:

data$country <- gsub("as\\.factor\\(country\\.x\\)", "", data$country) 
+0

谢谢!这样可行! – Tom

+2

另外,'fixed'选项似乎非常适合这种情况:'gsub(“as.factor(country.x)”,“”,data $ country,fixed = TRUE)'' – flodel

2
data$country <- with(data, { 
    country <- as.character(country) 
    factor(substr(country, 21, nchar(country))) 
}) 
相关问题