【问题标题】:R map delimited integers to delimited stringsR将分隔整数映射到分隔字符串
【发布时间】:2017-05-05 22:29:28
【问题描述】:

输入

我有以下数据框(标题到期和水果)。

我有以下向量:

index <- c("apple", "kiwi", "banana", "peach", "grape")

其中苹果 = 1,猕猴桃 = 2,香蕉 = 3,桃子 = 4,葡萄 = 5

输出

我想得到以下输出。

我该如何解决这个问题?

数据来源

myDf <- structure(list(expiry = 20161212:20161215, fruit = structure(c(4L, 
1L, 2L, 3L), .Label = c("2,4", "3,2", "4", "5,3,1"), class = "factor")), .Names = c("expiry", 
"fruit"), class = "data.frame", row.names = c(NA, -4L))


index <- c("apple", "kiwi", "banana", "peach", "grape")

【问题讨论】:

    标签: r indexing integer comma delimited


    【解决方案1】:

    在 tidyverse 中更具可读性:

    library(dplyr)
    library(purrr)
    
    df <- data_frame(expiry=c("20161212", "20161213", "20161214", "20161215"),
                     fruit=c("5,3,1", "2,4", "3,2", 4))
    
    index <- c("apple", "kiwi", "banana", "peach", "grape")
    
    by_row(df, function(x) {
    
      strsplit(x$fruit, ",")[[1]] %>%
        as.numeric() %>%
        map_chr(~index[.]) %>%
        paste0(collapse=",")
    
    }, .collate="cols", .to="fruit_names") %>%
      select(expiry, fruit=fruit_names)
    ## # A tibble: 4 × 2
    ##     expiry              fruit
    ##      <chr>              <chr>
    ## 1 20161212 grape,banana,apple
    ## 2 20161213         kiwi,peach
    ## 3 20161214        banana,kiwi
    ## 4 20161215              peach
    

    【讨论】:

    • 非常感谢您的帮助
    【解决方案2】:

    您可以使用sapplystrsplitas.numericas.character 来创建变量:

    myDf$fruit2 <- sapply(as.character(myDf$fruit), function(x) 
      paste0(index[as.numeric(strsplit(x, split = ",")[[1]])], collapse = ", "))
    

    【讨论】:

    • 非常感谢您的帮助
    • 抱歉,我还有一个问题。如果我的索引从 0 而不是 1 开始,这会起作用吗?所以在水果列中,有 x_i-1 代替(4 代替 5 ... 0 代替 1)。
    • 如果您的索引从 0 开始,则减 0 是正确的,即使用 index[as.numeric(.)-1] 而不是 index[as.numeric()]。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 2019-01-31
    • 2017-05-17
    • 2013-04-18
    相关资源
    最近更新 更多