R: Turning a data frame string into a character vector

Short version:

I do not understand the behavior of as.character when trying to convert one row of a data frame to a character vector.

> mydf <- data.frame("myvar1"=c("mystring","2"),"myvar2"=c("mystring","3")) > mydf # nice! myvar1 myvar2 1 mystring mystring 2 2 3 > as.character(mydf[1,]) [1] "2" "2" > as.character(as.vector(mydf[1,]) ) [1] "2" "2" 

Can someone please give me an explanation for the last two output lines and the correct approach? Many thanks.

Background / Purpose:

I want to use lre() to detect successive occurrences of values ​​in a row of a data frame (with columns of different data types).

Task: lre() requires a vector, vectors require a certain type of data (integer, character, coefficient, ...). My idea is to turn a data frame string into a character vector to avoid data loss by conversion.

+8
string type-conversion vector r
source share
2 answers

Your data frame columns are not characters; they are factors.

When you create a data frame, characters are used by default. You can see this clearly if you select a column

 R> mydf[,1] [1] mystring 2 Levels: 2 mystring 

To avoid this behavior, set the stringsAsFactors argument to FALSE

 mydf = data.frame("myvar1"=c("mystring", "2"), "myvar2"=c("mystring", "3"), stringsAsFactors=FALSE) 

You should also look at this question: How to convert a data frame column to a numeric type?

+7
source share

Try the following:

  mydf <- data.frame("myvar1"=c("mystring","2"),"myvar2"=c("mystring","3"), stringsAsFactors=F) as.character(mydf[1,]) [1] "mystring" "mystring" 

Your lines were brought to factors, and factor levels were shown to you.

+2
source share

All Articles