% group_by(ID) %>% summarise(Unique-6ren">
gpt4 book ai didi

r - 使用 R 在一行中查找唯一位置

转载 作者:行者123 更新时间:2023-12-04 21:13:49 25 4
gpt4 key购买 nike

考虑以下数据框:

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)

任何输入都会非常有用。

最佳答案

在 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))

关于r - 使用 R 在一行中查找唯一位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57214971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com