简体   繁体   中英

Use a character vector to extract columns from a dataframe in R

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 (eg "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.

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM