Reputation: 61
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.
Upvotes: 2
Views: 1916
Reputation: 21908
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
Upvotes: 1
Reputation: 388817
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
Upvotes: 2
Reputation: 145
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]))}
Upvotes: 0