【问题标题】:Finding the Unique Locations in a Row using R使用 R 查找连续的唯一位置
【发布时间】:2019-12-04 11:59:20
【问题描述】:

考虑以下data.frame:

df <- data.frame(ID = 1:2, Location = c("Love, Love, Singapore, Love, Europe, United States, Japan, Amazon, Seattle, Orchard Road, Love", 
                                        "Singapore, Singapore, Singapore") , stringsAsFactors = FALSE)

我想从上面提到的 df$Location 列中找出唯一数据,即我想获得一个新列,它只包含唯一的位置名称,就像下面提供的数据框一样;

df <- data.frame(ID = 1:2, Location = c("Love, Love, Singapore, Love, Europe, United States, Japan, Amazon, Seattle, Orchard Road, Love", 
                                        "Singapore, Singapore, Singapore") , 
                 Unique.Location = c("Love, Singapore, Europe, United States, Japan, Amazon, Seattle, Orchard Road",
                                     "Singapore"), stringsAsFactors = FALSE)

任何输入都会非常明显。

【问题讨论】:

标签: r dataframe


【解决方案1】:

在base R中,我们可以用逗号分割字符串,并为每个Location只粘贴unique字符串

df$unique.Location <- sapply(strsplit(df$Location, ","), function(x) 
                       toString(unique(trimws(x))))

或者使用tidyr::separate_rows的其他方式

library(dplyr)

df %>% 
  tidyr::separate_rows(Location, sep = ", ") %>%
  group_by(ID) %>%
  summarise(Unique.Location = toString(unique(Location)), 
            Location = toString(Location))

【讨论】:

    【解决方案2】:

    您可以使用strsplitsapplyunique 的组合:

    df$Unique.Location <- sapply(strsplit(df$Location, split = ", "), function(x) paste0(unique(x), collapse = ", "))
    

    【讨论】:

      【解决方案3】:

      使用tidyverse的选项

      library(dplyr)
      library(purrr)
      df %>% 
           mutate(unique.Location = str_extract_all(Location, "\\w+") %>%
                map_chr(~ toString(unique(.x))))
      

      【讨论】:

        猜你喜欢
        • 2018-05-23
        • 2015-10-14
        • 1970-01-01
        • 2016-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-23
        • 2017-06-26
        相关资源
        最近更新 更多