-1

Using the data.frame function in R, I am creating an example dataset. However, the vectors with strings are converted to a factor column.

How can I make vectors with strings (e.g. var1) become character column in my data set?

Current Code

df = data.frame(var1 = c("1","2","3","4"), 
                var2 = c(1,2,3,4)) 

Resulting Output

As shown below, var1 is a factor. I need var1 it to have the chr class.

> str(df)

'data.frame': 4 obs. of  2 variables:
$ var1 : Factor w/ 4 levels "1","2","3","4": 1 2 3 4
$ var2 : num  1 2 3 4

Trouble-shooting

Based on this post, I tried adding as.character, but var1 remains a factor.

df = data.frame(var1 = as.character(c("1","2","3","4")), 
                var2 = c(1,2,3,4))
Danielle
  • 733
  • 1
  • 10
  • 24

2 Answers2

2

stringsAsFactors is your friend. Namely:

df = data.frame(var1 = c("1","2","3","4"),var2 = c(1,2,3,4),stringsAsFactors = F) 

yielding:

> str(df)
'data.frame':   4 obs. of  2 variables:
 $ var1: chr  "1" "2" "3" "4"
 $ var2: num  1 2 3 4
amonk
  • 1,769
  • 2
  • 18
  • 27
0

Based on the comments, adding the argument stringsAsFactors=FALSE will create character variables instead of factor variables.

Danielle
  • 733
  • 1
  • 10
  • 24