Florent Florent - 2 months ago 8
R Question

How to insulate a character vector after a dataframe is created in R?

I have a dataframe with numeric and character columns and I would like to insulate to character vectors so that it doesn't return column name and factor levels when I select the data afterward.

My problem is that I create the dataframe with vectors containing numeric, boolean and character values, and for this reason I cannot use the insulate function

I()
at this stage.

conf1 <- c(name = "conf1", num = 1, bool = TRUE)
conf2 <- c(name = "conf2", num = 10, bool = TRUE)
conf3 <- c(name = "conf3", num = 100, bool = FALSE)

conf1 <- as.data.frame(t(conf1))
conf2 <- as.data.frame(t(conf2))
conf3 <- as.data.frame(t(conf3))

df <- cbind(conf1, conf2, conf3)


The dataframe is create, now I would like
df[1,]$name
to return only
"conf1"
and not the column name with all the levels.

df
name num bool
1 conf1 1 TRUE
2 conf2 10 TRUE
3 conf3 100 FALSE

df[1,]$name
name
conf1
Levels: conf1 conf2 conf3


Is there a possibility to do that without creating the dataframe with a 100% character vector like
name <- I(c("conf1", "conf2", "conf3"))
? (i.e. I would like to group the data per configuration)

It seems I'm unable to insulate the vector directly from the dataframe with :

df$name <- I(df$name)


Thank you

EDIT : I could convert data in numeric and character but this solution doesn't fit my need because it will overload my code (i.e. I select values from many rows and columns).

> as.character(df[1,]$name)
[1] "conf1"

> as.numeric(df[1,]$num)
[1] 1

Answer

As mentioned in my command. If it is not needed, that name is a factor, what would work is the following:

conf1 <- c(name = "conf1", num = 1, bool = TRUE)
conf2 <- c(name = "conf2", num = 10, bool = TRUE)
conf3 <- c(name = "conf3", num = 100, bool = FALSE)

And then instead of as.data.frame use data.frame with the parameter stringAsFactor=FALSE:

conf1 <- data.frame(t(conf1), stringsAsFactors = FALSE)
conf2 <- data.frame(t(conf2), stringsAsFactors = FALSE)
conf3 <- data.frame(t(conf3), stringsAsFactors = FALSE)

Creating the data.frame df as well with stringAsFactor=False yields then the following:

df <- data.frame(rbind(conf1,conf2,conf3), stringsAsFactors = FALSE)
 df$name[1]
[1] "conf1"

Df does than look like this:

> df
   name num  bool
1 conf1   1  TRUE
2 conf2  10  TRUE
3 conf3 100 FALSE