【问题标题】:Convert a data frame with integer columns to a list column, where each element in the list is an integer vector将具有整数列的数据框转换为列表列,其中列表中的每个元素都是整数向量
【发布时间】:2019-09-17 14:32:34
【问题描述】:

我想将 7 列数据框 icls 转换为整数向量的列表列。

 icols <- structure(list(CBT = c(0, 0, 0, 1, 1), MI = c(0, 1, 1, 1, 1), 
        Educ = c(0, 0, 0, 0, 0), Fam = c(0, 0, 0, 0, 0), CM = c(0, 
        0, 0, 0, 0), PeerGroup = c(0, 0, 0, 0, 0), ICM = c(0, 0, 
        0, 0, 0)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", 
    "data.frame"))

下面的代码创建了一个字符串向量。

  > do.call(paste, as.data.frame(icols))
    [1] "0 0 0 0 0 0 0" "0 1 0 0 0 0 0" "0 1 0 0 0 0 0" "1 1 0 0 0 0 0" "1 1 0 0 0 0 0"

我想创建一个列表列,其中每个字符串的7个元素变成一个整数向量。

所需的输出类似于:

     CBT    MI  Educ   Fam    CM PeerGroup   ICM  new_column
   <dbl> <dbl> <dbl> <dbl> <dbl>     <dbl> <dbl>   <list>
 1     0     0     0     0     0         0     0   <int [7]>
 ... 

【问题讨论】:

  • 你需要split(icols, 1:nrow(icols))
  • 如果你想作为矢量split(unlist(icols, use.names = FALSE), row(icols))

标签: r tidyverse purrr


【解决方案1】:

tidyverse 的一个选项是

library(tidyverse)
icols %>% 
    mutate(desired_column = pmap(., ~ c(..., use.names = FALSE)))
# A tibble: 5 x 8
#    CBT    MI  Educ   Fam    CM PeerGroup   ICM desired_column
#  <dbl> <dbl> <dbl> <dbl> <dbl>     <dbl> <dbl> <list>        
#1     0     0     0     0     0         0     0 <dbl [7]>     
#2     0     1     0     0     0         0     0 <dbl [7]>     
#3     0     1     0     0     0         0     0 <dbl [7]>     
#4     1     1     0     0     0         0     0 <dbl [7]>     
#5     1     1     0     0     0         0     0 <dbl [7]>     

如果 'desired_column' 应该是 integer

icols %>% 
    mutate(desired_column = pmap(., ~ c(..., use.names = FALSE) %>% 
              as.integer))

或者使用split 来自base R

icols$desired_column <- split(unlist(icols, use.names = FALSE), row(icols))

【讨论】:

  • 基本 R 中的映射版本同样是 icols$desired_column &lt;- do.call(Map, c(c,icols,use.names=FALSE))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-08
  • 1970-01-01
  • 2021-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-26
相关资源
最近更新 更多