rvectordataframecolors

Transform dput(remove) data.frame from txt file into R object with commas


I have a txt file (remove.txt) with these kind of data (that's RGB Hex colors):

"#DDDEE0", "#D8D9DB", "#F5F6F8", "#C9CBCA"...

Which are colors I don't want into my analysis.

And I have a R object (nacreHEX) with other data like in the file, but there are into this the good colors and the colors which I don't want into my analysis. So I use this code to remove them:

nacreHEX <- nacreHEX [! nacreHEX %in% remove] .

It's works when remove is a R object like this remove <- c("#DDDEE0", "#D8D9DB"...), but it doesn't work when it's come from a txt file and I change it into a data.frame, and neither when I try with remove2 <-as.vector(t(remove)).

So there is my code:

remove <- read.table("remove.txt", sep=",")
remove2 <-as.vector(t(remove))
nacreHEX <- nacreHEX [! nacreHEX %in% remove2]
head(nacreHEX)

With this, there are no comas with as.vector, so may be that's why it doesn't work.

How can I make a R vector with comas with these kind of data? What stage did I forget?


Solution

  • The problem is that your txt file is separated by ", " not ",'. The spaces end up in your string:

    rr = read.table(text = '"#DDDEE0", "#D8D9DB", "#F5F6F8", "#C9CBCA"', sep = ",")
    (rr = as.vector(t(rr)))
    # [1] "#DDDEE0"  " #D8D9DB" " #F5F6F8" " #C9CBCA"
    

    You can see the leading spaces before the #. We can trim these spaces with trimws().

    trimws(rr)
    # [1] "#DDDEE0"  "#D8D9DB" "#F5F6F8" "#C9CBCA"
    

    Even better, you can use the argument strip.white to have read.table do it for you:

        rr = read.table(text = '"#DDDEE0", "#D8D9DB", "#F5F6F8", "#C9CBCA"',
                        sep = ",", strip.white = TRUE)