在R函数中传递正确的参数

时间:2015-01-20 15:16:28

标签: r function arguments

嗨,我的数据框看起来像:

> head(Panel)
   Region Year Population TotalFedTax  BusIncTax IndivIncTax TotalFedSpend
1 Alabama 2000    4452173 18869238000 1541602000 16856323000   37650535757
2 Alabama 2001    4467634 18181072000 1064539000 16779861000   38739545139
3 Alabama 2002    4480089 18650989000 1867639000 16357183000   42052557014
4 Alabama 2003    4503491 17907240000 1472356000 16152532000   45395531847
5 Alabama 2004    4530729 18489339000 1931414000 16205117000   48874307713
6 Alabama 2005    4569805 20398808000 2198098000 17806684000   52057416455

我想创建一个函数来创建一个变量的映射,该映射是在给定年份从上面的Panel灵活创建的。例如," TotalFedSpend / Population"的地图在2000年将是:

temp <- subset(Panel, Year == 2000)
x <- data.frame(temp$Region, temp$TotalFedSpend / temp$Population)
title <- "TotalFedSpend / Population in 2000"
names(x) = c('region','value')
x[,1] = tolower(x[,1])
states <- data.frame(state.center, state.abb)
states_map <- map_data("state")
df = merge(x, states_map, by = "region")
p1 <- ggplot(data = df, aes(x = long, y = lat, group = group))
p1 <- p1 + geom_polygon(aes(fill = cut_number(value, 8)))
p1 <- p1 + geom_path(colour = 'gray', linestyle = 2)
p1 <- p1 + scale_fill_brewer('',palette = 'PuRd')
p1 <- p1 + ggtitle(title)
p1 <- p1 + coord_map()
p1

此代码本身可以正常工作,但是我在创建一个执行此映射的函数时遇到了问题,并且使用了灵活创建的系列。即我想创建一个功能,也可以映射系列,如&#34; BusIncTax + IndivIncTax在2010年&#34;。我不知道我应该传递什么样的参数,指定变量,以及如何修复第二个(x&lt; - data.frame ...)和第三行(title&lt; - ...)功能

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

temp <- subset(Panel, Year == 2000)
x <- data.frame(temp$Region, temp$TotalFedSpend / temp$Population)


ff <- function(v1, v2, v3, op, data) {
  attach(data)
  tmp = paste(v2,op,v3)
  x = eval(parse(text=tmp))
  return(x)
}

print(ff(Region, TotalFedSpend, Population, "+", temp))
print(ff(Region, TotalFedSpend, Population, "/", temp))

答案 1 :(得分:0)

temp <- subset(Panel, Year == 2000)
x <- data.frame(temp$Region, temp$TotalFedSpend / temp$Population)


ff <- function(v1, v2, v3, op, data) {
  attach(data)
  l = paste(v2,op,v3)
  #x = eval(parse(text=l))

  x <- data.frame(v1,eval(parse(text=l)))
  title <- "TotalFedSpend / Population in 2000"
  names(x) = c('region','value')
  x[,1] = tolower(x[,1])
  states <- data.frame(state.center, state.abb)
  states_map <- map_data("state")
  df = merge(x, states_map, by = "region")
  p1 <- ggplot(data = df, aes(x = long, y = lat, group = group))
  p1 <- p1 + geom_path(colour = 'gray', linestyle = 2)
  p1 <- p1 + scale_fill_brewer('',palette = 'PuRd')
  p1 <- p1 + ggtitle(title)
  p1 <- p1 + coord_map()
  p1
  return(p1)
  #return(x)
}