[R] Binding one column of characters into a dataframe factors other numeric columns

Marc Schwartz MSchwartz at MedAnalytics.com
Thu Mar 17 20:00:03 CET 2005


On Thu, 2005-03-17 at 18:30 +0000, Ken Termiso wrote:
> Hi all,
> 
> I searched through the archives, but couldn't find a fix...
> 
> Basically, I've got a bunch of numeric vectors and one character vector that 
> I want to bind into a data frame. When I include the character vector as a 
> column in the data frame, all the numeric columns get factored in the data 
> frame, which makes it tough to call those columns for calculations later on. 
> I've tried using AsIs to prevent this, but without luck...in the examples 
> below, the object named "c" is the one that is the character column. The 
> others are numeric.
> 
> df_without_char <- data.frame(cbind(rl, gl, cp), row.names = rownames(r)) 
> #without char vector
> 
> df_without_char <- data.frame(cbind(rl, gl, c, cp), row.names = 
> rownames(r))#with char vector
> 
> df <- data.frame(cbind(rl, gl, I(c), cp), row.names = rownames(r)) #try to 
> keep char vector AsIs
> 
> df <- data.frame(cbind(rl, gl, c=I(c), cp), row.names = rownames(r)) #try to 
> keep char vector AsIs
> 
> df <- data.frame(cbind(rl, gl, c, I(cp)), row.names = rownames(r)) #try to 
> keep num vector AsIs
> 
> df <- data.frame(cbind(rl, gl,  c, cp=I(cp)), row.names = rownames(r)) #try 
> to keep num vector AsIs


Don't use cbind() on all vectors, which will initially create a matrix
using a single data type.

Just list each vector separately. Try this:

rl <- 1:5
gl <- 6:10
cp <- 11:15
c <- letters[1:5]

df <- data.frame(rl, gl, cp, c)

> df
  rl gl cp c
1  1  6 11 a
2  2  7 12 b
3  3  8 13 c
4  4  9 14 d
5  5 10 15 e

> str(df)
`data.frame':	5 obs. of  4 variables:
 $ rl: int  1 2 3 4 5
 $ gl: int  6 7 8 9 10
 $ cp: int  11 12 13 14 15
 $ c : Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5


If you do not want 'c' to become a factor, you can use I() like this:

df <- data.frame(rl, gl, cp, I(c))

> str(df)
`data.frame':	5 obs. of  4 variables:
 $ rl: int  1 2 3 4 5
 $ gl: int  6 7 8 9 10
 $ cp: int  11 12 13 14 15
 $ c :Class 'AsIs'  chr [1:5] "a" "b" "c" "d" ...


You can of course still use the "row.names" argument as you are to set
the rownames in the data frame.


HTH,

Marc Schwartz




More information about the R-help mailing list