Seabass
Seabass

Reputation: 25

How to print outputs from a loop on one line?

I have to make a grade calculator in r which can convert numerical grades into letter grades. Here is the code I came up with:

numGrades<-(c(66,02,99,59,82))
for(i in 1:length(numGrades)) {
if (numGrades[i]>=90){
print("A")
} else if (numGrades[i]>=80){
print("B")
}  else if (numGrades[i]>=70){
print("C")
}  else if (numGrades[i]>=60){
print("D")
} else {
print("F")}
}

I can't find a way to integrate the cat or print(c()) functions so that it prints on one line rather than getting:

 [1] "D"`    
 [1] "F"`
 [1] "A"
 [1] "F"
 [1] "B"

If anyone has any ideas it would be greatly appreciated!

Upvotes: 1

Views: 1846

Answers (4)

Jilber Urbina
Jilber Urbina

Reputation: 61154

Just for the record, there's no need to use a for loop, you can use a nested ifelse

> graded2 <- ifelse(numGrades>=90, "A",
                    ifelse(numGrades >= 80 & numGrades < 90, "B",
                           ifelse(numGrades >= 70 & numGrades < 80, "C",
                                  ifelse(numGrades >= 60 & numGrades < 70, "E", "F"))))
> graded2
[1] "E" "F" "A" "F" "B"

Upvotes: 0

Nick Kennedy
Nick Kennedy

Reputation: 12640

With many tasks in R it’s better to do this using vectorised functions rather than loops. Here’s two ways of doing what you want, one using base R and the other dplyr::case_when. Note that cut returns a factor but you can always use as.character.

numGrades <- c(66,02,99,59,82)
letGrades <- cut(
  numGrades,
  breaks = c(-Inf, 6:9, Inf) * 10,
  labels = LETTERS[c(6, 4:1)],
  right = FALSE
)
letGrades

library(dplyr)
letGrades <- case_when(
  numGrades >= 90 ~ "A",
  numGrades >= 80 ~ "B",
  numGrades >= 70 ~ "C",
  numGrades >= 60 ~ "D",
  TRUE            ~ "F"
)
letGrades

Upvotes: 0

LocoGris
LocoGris

Reputation: 4480

why the cat is not working?

numGrades<-(c(66,02,99,59,82))
for(i in 1:length(numGrades)) {
  if (numGrades[i]>=90){
    cat("A ")
  } else if (numGrades[i]>=80){
    cat("B ")
  }  else if (numGrades[i]>=70){
    cat("C ")
  }  else if (numGrades[i]>=60){
    cat("D ")
  } else {
    cat("F ")}
}

Upvotes: 1

user2589273
user2589273

Reputation: 2467

I would simply use paste to join all elements of a 'graded' list. Hope this helps.

numGrades = graded = (c(66,02,99,59,82))

for(i in 1:length(numGrades)) {
if (numGrades[i]>=90){
graded[i] = "A"
} else if (numGrades[i]>=80){
graded[i] = "B"
}  else if (numGrades[i]>=70){
graded[i] = "C"
}  else if (numGrades[i]>=60){
graded[i] = "E"
} else {
graded[i] = "F"}
}

print(paste(graded))

This gives:

> print(paste(graded))
[1] "E" "F" "A" "F" "B"

Upvotes: 1

Related Questions