【问题标题】:print rearranged dataframe to screen with loops or `purrr::map()`使用循环或“purrr::map()”将重新排列的数据帧打印到屏幕上
【发布时间】:2019-12-27 12:10:28
【问题描述】:

我有这样形式的数据(下面的可重现代码):

#>   y x char
#> 1 1 1    a
#> 2 1 2    b
#> 3 1 3    c
#> 4 2 1    d
#> 5 2 2    e
#> 6 2 3    f
#> 7 3 1    g
#> 8 3 2    h
#> 9 3 3    i
df <- data.frame(stringsAsFactors=FALSE,
           y = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
           x = c(1, 2, 3, 1, 2, 3, 1, 2, 3),
        char = c("a", "b", "c", "d", "e", "f", "g", "h", "i")
)
df

是否有一种简单的方法可以使用y 值作为 y 轴、x 值作为 x 轴和第三列 (char) 作为值来打印到屏幕? map() 的解决方案会很棒。

所以我想要的输出看起来像

   abc
   def
   ghi

我开始尝试遍历 y 和 x,以期使用 purrr::map(),但还没有走多远。

if (df$y==1 & df$x==1){
print(df$char)
  }

【问题讨论】:

    标签: r loops tidyverse purrr


    【解决方案1】:

    这就是tidyr::spread() 的用途:

    spread(df, x, char)
    

    【讨论】:

      【解决方案2】:

      您还可以将 data.frame 转换为matrix

      a <- matrix(
        data = df$char, 
        nrow = length(unique(df$x)), 
        ncol = length(unique(df$y)),
        "dimnames" = list(unique(df$y), unique(df$x)),
        byrow = TRUE
      )
      

      它将是:

        1   2   3  
      1 "a" "b" "c"
      2 "d" "e" "f"
      3 "g" "h" "i"
      

      根据需要将字符串连接成一列:

      for (r in 1:nrow(a)) {
         print(paste(a[r, ], collapse = ''))
      }
      
      [1] "abc"
      [1] "def"
      [1] "ghi"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-12
        • 2019-01-10
        • 1970-01-01
        • 2020-08-05
        • 2018-07-02
        • 2015-08-13
        • 2016-08-12
        • 2018-10-14
        相关资源
        最近更新 更多