1

I have a dataframe

a = c("A","B","C")
b = c(12,13,14)
c = ("Great","OK","Bad")

df = data.frame(a,b,c)

I want to print out every row with all the columns Expected output:

A is 12 mins and it is Great
B is 13 mins and it is OK
C is 14 mins and it is Bad

I tried to use cat or paste0 but it does not work as what I want.

Oli
  • 9,766
  • 5
  • 25
  • 46
Joe Ng
  • 51
  • 6

3 Answers3

1

You may use sprintf -

with(df, sprintf('%s is %d mins and it is %s', a, b, c))

#[1] "A is 12 mins and it is Great" "B is 13 mins and it is OK"    
#[3] "C is 14 mins and it is Bad" 

If you need this for display purpose with each row in a new line add paste0 with cat.

cat(with(df, paste0(sprintf('%s is %d mins and it is %s', a, b, c), collapse = '\n')))

#A is 12 mins and it is Great
#B is 13 mins and it is OK
#C is 14 mins and it is Bad
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

You can also make use of glue package for this in a way that whatever you put between curly braces within a quoted string in glue function will be evaluated as R code:

library(dplyr)
library(glue)

df %>%
  mutate(out = glue("{a} is {b} mins and it is {c}"))
 
# A tibble: 3 x 4
  a         b c     out                         
  <chr> <dbl> <chr> <glue>                      
1 A        12 Great A is 12 mins and it is Great
2 B        13 OK    B is 13 mins and it is OK   
3 C        14 Bad   C is 14 mins and it is Bad
Anoushiravan R
  • 21,622
  • 3
  • 18
  • 41
0

joe NG, i wouldnt suggest you create a data frame when you can use separate vectors to get the desired output, however there could be many more ways to get you desired output.

a = c("A","B","C")
b = c(12,13,14)
c = c("Great","OK","Bad")
# create loop 
d <- c(1:3)
# loop script to print output
for (x in 1:3){
print(paste0(a[x]," is ",b[x]," mins and it is  ",c[x]))}
Arslan Sh.
  • 145
  • 7