如何提取数据框中每一行中的唯一值?

ybc*_*204 5 r unique delimited dataframe

我试图在 R 中的数据帧的每一行中提取唯一值,而不使用 for 循环。

df <- data.frame(customer = c('joe','jane','john','mary'), fruit = c('orange, apple, orange', NA, 'apple', 'orange, orange'))

df

  customer                 fruit
1      joe orange, apple, orange
2     jane                  <NA>
3     john                 apple
4     mary        orange, orange
Run Code Online (Sandbox Code Playgroud)

我想要的专栏内容fruit是:“橙色,苹果”,NA,“苹果”,“橙色”

  customer                 fruit
1      joe         orange, apple
2     jane                  <NA>
3     john                 apple
4     mary                orange
Run Code Online (Sandbox Code Playgroud)

我尝试了一些类似的事情

apply(df, 1, function(x) unique(unlist(str_split(x[, "fruit"], ", "))))
Run Code Online (Sandbox Code Playgroud)

它不起作用。

如何获取数据框中每一行的唯一值?

Ano*_*n R 0

更新的解决方案 我刚刚修改了我的代码以匹配您希望的输出。

library(dplyr)
library(tidyr)

df %>%
  separate_rows(fruit) %>%
  distinct(customer, fruit) %>%
  group_by(customer) %>%
  summarise(fruit = paste(sort(fruit, na.last = FALSE), collapse = ", "))

# A tibble: 4 x 2
  customer fruit        
  <chr>    <chr>        
1 jane     NA           
2 joe      apple, orange
3 john     apple        
4 mary     orange

Run Code Online (Sandbox Code Playgroud)