我有一个数据框架
a = c("A","B","C")
b = c(12,13,14)
c = ("Great","OK","Bad")
df = data.frame(a,b,c)
我想打印出每行和所有列预期的输出:
A is 12 mins and it is Great
B is 13 mins and it is OK
C is 14 mins and it is Bad
我尝试使用cat
或paste0
,但它不像我想要的那样工作。
您可以使用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"
如果您需要将paste0
与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
您也可以使用glue
包来实现这一点,在glue
函数中,在引号字符串内的花括号之间的任何内容都将被计算为R代码:
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
joe NG,当你可以使用单独的向量来获得所需的输出时,我不建议你创建一个数据帧,但是可以有更多的方法来获得所需的输出。
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]))}