2017-12-02 15 views
1

我似乎在将新函数应用于特定数据集时遇到了问题。在多边形上应用用户定义的函数以从R中的特定数据集迭代地绘制圆形

我已经定义了一个函数“circle”,它将中心的x坐标x和y坐标y以及半径r作为参数,并绘制顶点为(x + r sin(ti) ; y + rcos(ti)),其中ti是从0到2的长度为100的序列。提供给圆的附加参数被传递到多边形。

功能看起来像这样:

circle<-function(x,y,r,...) {  
ti<-seq(0,(2*pi),length.out = 100)   
polygon(x + r *sin(ti),y+r*cos(ti),...) 
} 

我已经然后修改的功能,使得它也可以如果x,y和r为长度的矢量> 1.

它看起来像这样:

circle<-function(x,y,r,...) { 
ti<-seq(0,(2*pi),length.out = 100) 
data.fun<-as.data.frame(cbind(x,y,r)) 
for (i in 1:nrow(data.fun)) { 
polygon(x[i] + r[i] *sin(ti),y[i]+r[i]*cos(ti),...) 
    } 

} 

所以,当我使用:

plot(c(-3,3), c(-3,3), type="n") 
circle(c(0,2), c(0,0), c(1, 0.5)) 

它在右侧绘制一个小圆圈。

但是,当我尝试将函数应用于给定的数据集并使用x,y和r的列名时,它不起作用。

的数据是这样的:

head(health) 
Country  Region Population LifeExpectancy HealthExpenditure 
Albania  Europe  3204284  76.90095  2.202286 
Algeria Middle East 35468208  72.85254  1.981556 
Angola  Africa  19081912  50.65366  1.461099 
Argentina Latin America 40412376  75.63215  7.592994 
Armenia Europe  3092072  73.78356  1.337856 
Australia East Asia 22065300  81.69512  51.735024 

我需要建立对卫生支出plotof预期寿命(在100的$)。该图应该包含圆圈 (半径 sqrt(人口[i])/ 10000)(HealthExpenditure [i] LifeExpectancy [i]),并且每个圆圈的填充颜色应该为 表示该区域。

然而,当我试图

circle(HealthExpenditure,LifeExpectancy,(sqrt(Population)/1000)), 

的功能不起作用。 我也尝试重新定义列名作为默认值的函数没有成功。

我该如何将函数应用到上面的列名并逐个绘制国家的圈子? (我试图使用MASS中的eqscplot函数。)

回答

1

考虑mapply在相同长度的向量上(即多次应用)按元素运行迭代。采用这种方法,您无需在定义的函数内运行for循环。下面输出采用原装版本完全一样发布的尝试,circle(c(0,2), c(0,0), c(1, 0.5)),在for环版本:

circle <- function(x, y, r,...) {  
    ti <- seq(0, (2*pi), length.out = 100)   
    polygon(x + r *sin(ti), y+r*cos(ti),...) 
} 

df <- data.frame(x=c(0,2), y=c(0,0), z=c(1, 0.5)) 

plot(c(-3,3), c(-3,3), type="n") 
mapply(circle, df$x, df$y, df$z) 

对于实际数据帧,同样使用mapply。当然,调整情节尺寸和数据帧的名字,​​DF,因此:

df <- read.table(text='Country  Region Population LifeExpectancy HealthExpenditure 
Albania  Europe  3204284  76.90095  2.202286 
Algeria "Middle East" 35468208  72.85254  1.981556 
Angola  Africa  19081912  50.65366  1.461099 
Argentina "Latin America" 40412376  75.63215  7.592994 
Armenia Europe  3092072  73.78356  1.337856 
Australia "East Asia" 22065300  81.69512  51.735024', header=TRUE) 

# COLOR FILL AND COLOR BORDER ADDED 
circle <- function(x, y, r, c,...) {  
    ti <- seq(0, (2*pi), length.out = 100)   
    polygon(x + r *sin(ti), y+r*cos(ti),col=c,border=c,...) 
} 
# RANDOMLY SAMPLE FROM palette() 
color_list <- sample(rep(palette(), nrow(df)), nrow(df), replace=TRUE) 

plot(c(0,100), c(0,100), type="n") 
output <- mapply(circle, df$HealthExpenditure, df$LifeExpectancy, (sqrt(df$Population)/1000), color_list) 

Circle Polygon Plot

+0

谢谢您的回复芭菲。我试过这个解决方案,但不幸的是,该命令对每一行都返回NULL,并且它不显示任何内容。我仍然不知道什么可能是错的。 – red22

+0

使用您发布的数据查看更新,我只调整绘图的x和y坐标。我甚至添加了作为另一个矢量的颜色。您可以将'mapply'分配给像* output *这样的对象,以避免打印出NULL值。 – Parfait

相关问题