Arun
Arun

Reputation: 625

R:: How to make a dataframe and attach its column names in a single line in R

I have a data frame like this:

parList <- as.data.frame( rbind(
  c("PACKAGE"    ,"OptimizeR"              ),
  c("RCALL"      ,"optimizeR_jar"          ),
  c("var_PRODUCT", "PRODUCT_CODE"          ),
  c("var_JAR"    ,"SUGAR_JAR"              ),
  c("var_JAR"    ,"STRENGTH_JAR"           ),
  c("candidat"   ,"C18"                    ),
  c("benchmark"  ,"L23"                    ),
  c("var_TARGET" ,"PRODUCT_OVERALL_OPINION")
)
)

The column names can be attached like this

names(parList) <- c("CODE", "VAL")

I want to make both in a single line of code. Please advice how this can be achieved? Thank you

Upvotes: 1

Views: 30

Answers (1)

akrun
akrun

Reputation: 886948

We can use setNames

parList <- setNames(as.data.frame(..., c("CODE", "VAL"))

Or if we are using data.table, setnames can be used

library(data.table)
parList1 <- setnames(setDT(transpose(lst)), c("CODE", "VAL"))[]

where

lst <- list(c("PACKAGE"    ,"OptimizeR"              ),
            c("RCALL"      ,"optimizeR_jar"          ),
            c("var_PRODUCT", "PRODUCT_CODE"          ),
            c("var_JAR"    ,"SUGAR_JAR"              ),
            c("var_JAR"    ,"STRENGTH_JAR"           ),
            c("candidat"   ,"C18"                    ),
            c("benchmark"  ,"L23"                    ),
            c("var_TARGET" ,"PRODUCT_OVERALL_OPINION"))

Upvotes: 3

Related Questions