David
David

Reputation: 67

Issues creating an if else statement for rounding with a loop in R

I'm struggling with code for an R class. We are working on loops and I'm supposed to round numbers within a dataframe up if they have a decimal greater than .6, round down if a decimal <0.4 and leave alone if in between. I cannot get this to work.

Dataframe:

 set.seed(12)
 df<-data.frame(rgamma(n=20,shape=4,scale=2),runif(n=20),rnorm(n=20),paste("Observation",1:20))
 colnames(df)<-c("V1","V2","V3","Obs")

Here is the code I've tried:

rounddf<-rep(nrow(df),ncol(df)-1) 
for (i in 1:ncol(df)-1) 
{
for (j in 1:nrow(df)) 
 {
  if (i>0.6)
   {rounddf[i]<-ceiling(df[i]) 
    } else if (i<0.4){rounddf[i]<-floor(df[i])}
  }
}
rounddf

Upvotes: 1

Views: 472

Answers (1)

Maxwell Chandler
Maxwell Chandler

Reputation: 642

The key is to create an empty data frame and populate it by using the i and j in the for loop to index those values in the new data frame. This code will do exactly what you want. You also have to make sure to reduce your numbers into fractions so that the part that is larger than 1 is hidden. Then you can use if else statements to evaluate them.

   set.seed(12)
   df<-data.frame(rgamma(n=20,shape=4,scale=2),
   runif(n=20),rnorm(n=20),paste("Observation",1:20))
   colnames(df)<-c("V1","V2","V3","Obs")


   newdf <-data.frame( V1=rep(0,20), V2=rep(0,20), V3=rep(0,20))



   df <- df[,1:3, drop=TRUE]

    for (i in 1:ncol(df)) 
   {
   for (j in 1:nrow(df)) 
   {n <- df[j,i]
   whole <- floor(df[j,i])
   fraction <- n-whole
   if(fraction > .60)  newdf[j,i] <- ceiling(df[j,i])
   if(fraction < .40) newdf[j,i] <- floor(df[j,i])
   if((fraction > .4) & (fraction < .6)) newdf[j,i] <- df[j,i] }}

Upvotes: 1

Related Questions