【问题标题】:Print multiple variables in one line in r在r中的一行中打印多个变量
【发布时间】:2021-12-13 12:02:05
【问题描述】:

我有一个数据框

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

我尝试使用catpaste0,但它并不能如我所愿。

【问题讨论】:

标签: r dataframe


【解决方案1】:

你可以使用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" 

如果您需要在新行中的每一行进行显示,请添加 paste0cat

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

【讨论】:

    【解决方案2】:

    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]))}
    

    【讨论】:

      【解决方案3】:

      您还可以为此使用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
      

      【讨论】:

        猜你喜欢
        • 2013-10-10
        • 2016-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-28
        • 1970-01-01
        • 2010-12-25
        • 2016-01-04
        相关资源
        最近更新 更多