【问题标题】:converting numeric arrays into list and savig in CSV in R将数值数组转换为列表并在 R 中的 CSV 中保存
【发布时间】:2021-08-25 10:23:31
【问题描述】:

我正在尝试以不常见的形式存储两个数值数组,例如c('[1;2;3]','[4;5;6]','[24;25;26]')

我需要它们在单个单元格中的 CSV 中,就像这里

到目前为止,我尝试过这个:

DF
ID time Y
1  3    23
1  4    24
1  5    20 
2  2    12
2  8    15
3  2    19
3  3    23
3  5    21
3  6    32

timeList = list()
yList = list()
for (i in 1:3) {
  timeList[i] = DF$time
  yList[i] = DF$Y   
}

longTimeList = list(timeList)
longYList = list(yList)

DF <- data.frame(ID = c(1,2,3),
             P1 = longTimeList,
             P2 = longYList)

所以示例 DF 将读取

 newDF <- data.frame(ID = c(1,2,3),
                 P1 = c('[3;4;5]','[2;8]','[2;3;5;6]'),
                 P2 = c('[23,24,20]','[12;15]','[19;23;21;32]'))

应该存储在 CSV 文件中,以提供类似于上面显示的内容。

【问题讨论】:

  • 欢迎来到 Stackoverflow,您提出了一个有趣的问题,其中包含您正在尝试的数据和代码、您想要的结果,并且您会得到一些经过深思熟虑的答案。您的最后一个挑战是通过单击您选择的答案旁边的检查来选择最适合您的答案。这完成了这里的良性循环,因为它标志着这是一个已回答的问题,将来对其他人有用。并再次欢迎。

标签: r arrays csv


【解决方案1】:

glue 的选项

library(dplyr)
library(glue)
library(stringr)
df %>% 
    group_by(ID) %>% 
    summarise(across(everything(), function(x)
      glue("[{str_c(x, collapse = ';')}]")))
# A tibble: 3 x 3
#     ID time      Y            
#  <int> <glue>    <glue>       
#1     1 [3;4;5]   [23;24;20]   
#2     2 [2;8]     [12;15]      
#3     3 [2;3;5;6] [19;23;21;32]

【讨论】:

    【解决方案2】:

    使用 tidyverse

    df <-
      structure(list(
        ID = c(1L, 1L, 1L, 2L, 2L, 3L, 3L, 3L, 3L),
        time = c(3L,
                 4L, 5L, 2L, 8L, 2L, 3L, 5L, 6L),
        Y = c(23L, 24L, 20L, 12L, 15L,
              19L, 23L, 21L, 32L)
      ),
      class = "data.frame",
      row.names = c(NA,
                    -9L))
    
    library(tidyverse)
    df %>% 
      group_by(ID) %>% 
      summarise(across(everything(), ~paste0(.x, collapse = ";"))) %>% 
      mutate(across(c(time, Y), ~paste0("[", .x, "]")))
    #> # A tibble: 3 x 3
    #>      ID time      Y            
    #>   <int> <chr>     <chr>        
    #> 1     1 [3;4;5]   [23;24;20]   
    #> 2     2 [2;8]     [12;15]      
    #> 3     3 [2;3;5;6] [19;23;21;32]
    

    reprex package (v2.0.0) 于 2021-06-08 创建

    【讨论】:

      【解决方案3】:

      相信aggregate可以帮到你

      > aggregate(. ~ ID, DF, function(x) sprintf("[%s]", paste0(x, collapse = ";")))
        ID      time             Y
      1  1   [3;4;5]    [23;24;20]
      2  2     [2;8]       [12;15]
      3  3 [2;3;5;6] [19;23;21;32]
      

      【讨论】:

        猜你喜欢
        • 2022-01-18
        • 1970-01-01
        • 1970-01-01
        • 2022-01-06
        • 2016-04-22
        • 1970-01-01
        • 2021-03-10
        • 1970-01-01
        • 2021-09-06
        相关资源
        最近更新 更多