使用data.frame的列名

时间:2016-12-15 02:39:47

标签: r anova

我有以下(简化)文本文件,名为import pygame,sys pygame.init() screen = pygame.display.set_mode((800, 800)) tm = 20 # Terminal Velocity gravity = 1 class Player: def __init__(self,speed,x,y): self.speed = speed self.x = x; self.y = y self.yVelocity = 0 self.xVelocity = 0 def getKeys(self): key = pygame.key.get_pressed() if key[pygame.K_a]: self.xVelocity -= self.speed if key[pygame.K_d]: self.xVelocity += self.speed if key[pygame.K_SPACE]: if isGround(self.x,self.y): self.yVelocity -= 20 def move(self,dt): if self.x < 0: self.x = 0 if self.x > 800-15: self.x = 800-15 if self.y < 0: self.y = 0 if self.y > 800-10: self.y = 800-10 self.x += self.xVelocity self.y += self.yVelocity if self.xVelocity != 0: self.xVelocity /= 70*dt if self.yVelocity < tm and not isBlocking(self.x,self.y+self.yVelocity): self.yVelocity += gravity if isBlocking(self.x,self.y): self.yVelocity = 0 def draw(self): screen.fill((255,0,0),(self.x,self.y,10,10)) def isBlocking(x,y): if x < 0 or x > 800 or y < 0 or y > 800: return True elif y >= 400: return True else: return False def isGround(x,y): if y >= 400: return True else: return False player = Player(1,400,400) clock = pygame.time.Clock() while True: dt = clock.tick(60)/1000 # limit to 60 FPS. screen.fill((0,0,0)) if pygame.event.poll().type == pygame.QUIT: pygame.quit(); sys.exit() player.getKeys() player.move(dt) player.draw() pygame.display.flip()

datafile.txt

在此文本文件中,我创建了data.frame Height Color Sales short blue 24 short blue 25 short red 31 short red 28 short black 35 short black 32 tall blue 31 tall blue 32 tall red 36 tall red 32 tall black 41 tall black 36

data

通过以下行,我可以执行双向 ANOVA

data <- read.table("datafile.txt", header = TRUE)

但是,我希望执行双向 ANOVA 的以下代码不起作用:

anova(lm(Sales ~ Height*Color, data))

我想使用从data.frame中提取的列名来执行分析,而不是直接键入columnNames <- names(data) anova(lm(columnNames[3] ~ columnNames[1]*columnNames[2], data)) SalesHeight。我非常感谢你的帮助。

1 个答案:

答案 0 :(得分:2)

我们需要使用paste并转换为formula

anova(lm(formula(paste(columnNames[3], "~",  columnNames[1], "*", columnNames[2])), data))

甚至不需要明确的formula

anova(lm(paste(columnNames[3], "~",  columnNames[1], "*", columnNames[2]), data))
#Analysis of Variance Table

#Response: Sales
#             Df Sum Sq Mean Sq F value   Pr(>F)   
#Height        1  90.75  90.750 17.8525 0.005529 **
#Color         2 128.17  64.083 12.6066 0.007103 **
#Height:Color  2   3.50   1.750  0.3443 0.721876   
#Residuals     6  30.50   5.083                    
#---
#Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1