【问题标题】:Creating a list of repetitions from a table从表中创建重复列表
【发布时间】:2020-06-08 19:14:24
【问题描述】:

我想创建一个有两列的表,第一列是一个数字,第二列是不同字符串的重复,从一个表中得到每个字符串的重复次数。

我的意思是:

1/ 我有这个:

A 1,3 #("A" 从 1 到 3)

B 4,5

C 6,9

...

2/ 我想要这个:

1 个

2 个

3A

4 乙

5 乙

6C

7C

8C

9℃ ...

谢谢

【问题讨论】:

  • 你好弗朗西斯科,欢迎来到 SO。你把你的问题说清楚了。但是,仍然很难回答。您使用的数据结构到底是什么?你的标签说list。在你的问题中你说table。如果您能给我们提供 R 格式的数据样本,可以在我们自己的系统上读取,我们可以帮助您找到解决方案。但是如果不知道确切的数据结构,就很难并且需要大量猜测。

标签: r list


【解决方案1】:

我们可以在,处拆分'col2',通过循环list并转换为numeric,然后unnest'col2'来创建一个序列

library(dplyr)
library(purrr)
library(tidyr)
df1 %>%
   mutate(col2 = map(strsplit(col2, ","), ~ {
          x1 <- as.numeric(.x)
           x1[1]:x1[2]})) %>%
    unnest(c(col2))
# A tibble: 9 x 2
#  col1   col2
#  <chr> <int>
#1 A         1
#2 A         2
#3 A         3
#4 B         4
#5 B         5
#6 C         6
#7 C         7
#8 C         8
#9 C         9

数据

df1 <- data.frame(col1 = c('A', 'B', 'C'),
     col2 = c('1,3', '4,5','6,9'), stringsAsFactors = FALSE)

【讨论】:

    【解决方案2】:

    你可以试试这个:

    df <- data.frame(
      V1 = LETTERS[1:3],
      V2 = c("1,3", "4,5", "6,9")
    )
    
    split_idx <- strsplit(df$V2, ",") # split V2 into two parts
    split_idx <- t(list2DF(split_idx)) # puts the values column wise 
    
    split_idx <- apply(split_idx, 2, as.numeric)
    
    colnames(split_idx) <- c("from", "to") # e.g., in "1,3", 1 would be `from`, and 3 is `to`. 
    
    df <- data.frame(df, split_idx)
    
    out <- list()
    
    for (i in seq_along(df$V1)) {
      out[[i]] <- c(df[["V1"]][[i]], rep(
        df[[1]][[i]],
        df[["to"]][[i]] - df[["from"]][[i]]
      ))
    }
    
    V1 = unlist(out)
    
     df <- data.frame(V1, idx = seq_along(V1))
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-12
      • 2011-11-10
      • 2016-10-21
      • 1970-01-01
      • 2019-09-25
      • 1970-01-01
      • 2018-06-25
      • 2015-10-16
      相关资源
      最近更新 更多