简体   繁体   中英

Using Apply on a data.frame with character and numeric variables

I'm trying to convert some exsiting loop based code to use R's apply function. As per the specs fo this project, no additional libraries (eg plyr) are allowed.

This is how it currently works.

  Type Pressure Temp 1 Iron 100 10 2 Copper 200 20 
for(i in 1:rnow(data))
{
    if(data$Type[i] == "Iron")
         Output[i] <- IronCalculation(data$Pressure[i]...)
    else if(data$Type[i] == "Copper")
         Output[i] <- CopperCalculation(data$Pressure[i]...)
}

I want to convert this to use the apply() function. I've tried a number of ways, but I'm simply stuck because apply() converts all variable values into characters, and so numeric compilations on these are not possible. The original data set has 150+ variables, many of which are strings/characters.

As a test I've tried the following. Obviously it fails. I can convert the the character variables to numbers using as.numeric(), but there are 8000+ rows and 20 variables in each. Seems like waste of CPU cycles.

apply(data[1,], 2, function(x) {
if(x['Type'] == "Iron")
             Output <- IronCalculation(x['Type'],x['Pressure']...)
})

Can anybody help? How can I change this loop to use an apply function?

Try

apply(data, 1,  
  function(x) {  
    if (x['Type'] == 'Iron')  
      IronCalculation(as.numeric(x['Pressure']), as.numeric(x['Pressure']))  
    else if (x['Type'] == 'Copper')  
      CopperCalculation(as.numeric(x['Pressure']), as.numeric(x['Pressure']))  
  }  
)  

and you will get a vector. as.numeric() is necessary because both Pressure and Temp are coerced to character when passed along with Type to your anonymous function.

Edit: But using switch() as suggested by @Justin instead of nested if s would be much more ellegant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM