2021年4月9日星期五

How to extract unique values within each row in dataframe in R

I am trying to extract unique values within each rows of dataframe in R without using for loop.

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  

What I want for the fruit column is: 'orange, apple', NA, 'apple', 'orange'

  customer                 fruit  1      joe         orange, apple  2     jane                  <NA>  3     john                 apple  4     mary                orange  

I tried something along the lines of

apply(df, 1, function(x) unique(unlist(str_split(x[, "fruit"], ", "))))  

and it is not working.

How can I get unique values within each row in the dataframe?

https://stackoverflow.com/questions/67028284/how-to-extract-unique-values-within-each-row-in-dataframe-in-r April 10, 2021 at 05:05AM

没有评论:

发表评论