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 column 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 doesnt work as what I want
CodePudding user response:
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]))}
CodePudding user response:
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