Home > Enterprise >  Use a character vector to extract columns from a dataframe in R
Use a character vector to extract columns from a dataframe in R

Time:11-30

I have the following character vector

Group1
[1] "c(\"Ca\", \"Mg\", \"SO4\", \"HCO3\", \"NO3\", \"Cr\", \"Ni\", \"Sr\")"
> class(Group1)
[1] "character"

and I want το use the elements of Group1 (e.g. "Ca") to extract columns from a dataframe (df) based on colnames() function.

colnames(df) <- Group1

I have tried it but it did not work. My guess is that I need to remove the "" symbol.

CodePudding user response:

First you need to parse your character and then evaluate.

Group1 <- "c(\"Ca\", \"Mg\", \"SO4\", \"HCO3\", \"NO3\", \"Cr\", \"Ni\", \"Sr\")"

Group1b <- parse(text = Group1)
Group1c <- eval(Group1b)

To receive

> Group1c
[1] "Ca"   "Mg"   "SO4"  "HCO3" "NO3"  "Cr"   "Ni"   "Sr" 

*EDIT I forgot to ask, why is this stored as text to start with? If you typed this you actually needed Group1 <- c("Ca", "Mg", "SO4", "HCO3", "NO3", "Cr", "Ni", "Sr")

CodePudding user response:

colnames is used to set / rename your column names, as you mention that you want to extract the columns in Group1 from your data.frame, you probably want this:

Group1 <- c("Ca", "Mg", "SO4", "HCO3", "NO3", "Cr", "Ni", "Sr")
df[names(df) %in% Group1]
  • Related