Anthony Damico
2011-Jul-22 00:06 UTC
[R] Recoding Multiple Variables in a Data Frame in One Step
Hi, I can't for the life of me find how to do this in base R, but I'd be surprised if it's not possible. I'm just trying to replace multiple columns at once in a data frame. #load example data data(api) #this displays the three columns and eight rows i'd like to replace apiclus1[ apiclus1$meals > 98 , c( "pcttest" , "api00" , "sch.wide" ) ] #the goal is to replace pcttest with 100, api100 with NA, and sch.wide with "Maybe" #this doesn't work-- apiclus1[ apiclus1$meals > 98 , c( "pcttest" , "api00" , "sch.wide" ) ] <- c( 100 , NA , "Maybe" ) #the results replace downward instead of across apiclus1[ apiclus1$meals > 98 , c( "pcttest" , "api00" , "sch.wide" ) ] I know I can do this with a few more steps (like one variable at a time or by counting the number of rows to replace and then using rep() ..but I'm hoping there's a quicker way? Thanks!! Anthony Damico Kaiser Family Foundation using R 2.13.0 in Windows x64 [[alternative HTML version deleted]]
David Winsemius
2011-Jul-25 22:38 UTC
[R] Recoding Multiple Variables in a Data Frame in One Step
On Jul 21, 2011, at 8:06 PM, Anthony Damico wrote:> Hi, I can't for the life of me find how to do this in base R, but > I'd be > surprised if it's not possible. > > I'm just trying to replace multiple columns at once in a data frame. > > #load example data > data(api) > > #this displays the three columns and eight rows i'd like to replace > apiclus1[ apiclus1$meals > 98 , c( "pcttest" , "api00" , > "sch.wide" ) ] > > > #the goal is to replace pcttest with 100, api100 with NA, and > sch.wide with > "Maybe" > > #this doesn't work-- > apiclus1[ apiclus1$meals > 98 , c( "pcttest" , "api00" , > "sch.wide" ) ] <- > c( 100 , NA , "Maybe" ) > > #the results replace downward instead of across > apiclus1[ apiclus1$meals > 98 , c( "pcttest" , "api00" , > "sch.wide" ) ]If I had noted that I would have tried this: apiclus1[ apiclus1$meals > 98 , rep( c( "pcttest" , "api00" , "sch.wide" ), each = sum(apiclus1$meals > 98) ) ] Should be pretty easy to test, but since _you_ are the one responsible for providing examples for testing when posting to rhelp, I am going to throw an untested theory back at you.> > I know I can do this with a few more steps (like one variable at a > time or > by counting the number of rows to replace and then using rep() ..but > I'm > hoping there's a quicker way? > > > Thanks!! > > Anthony DamicoDavid Winsemius, MD West Hartford, CT