anup
anup

Reputation: 475

Change column class of df in R

I started with an empty df.

 > df <- data.frame("coeff" = numeric(), "value" = numeric(), "Type" = character()) 

Now I added a few rows to this df in the following way.

> df<- rbind(df,c(0.05,sum(main$c1), "BaseLine"), stringsAsFactors = FALSE )

Note: main is another df, sum of col c1 need is added here. (nothing to worry about procedure up to this point). With this method, I added some rows to df. Since the last field in this code is character, rbind converted all columns into character.

I have two questions.

  1. Is there a way around to use rind where it does not follow the hierarchy: raw < logical < integer < double < complex < character < list as described in rbind help?

  2. Is there a way to convert all numeric class to character and retain values in character class without insertion of NAs?
    for eg. when using:
    > sapply(df, as.numeric) the values in column Type in the df changed to NAs.

I am looking for some function which would convert character fields containing numbers to numeric while leaving the character fields containing characters as it is.

I don't want to use:
df$coeff <- as.numeric(df$coeff)
df$value <- as.numeric(df$value)
because I have many columns and the number of columns changes everytime I read the input from a shapefile.

Upvotes: 2

Views: 1283

Answers (1)

pieca
pieca

Reputation: 2563

The problem is that c(0.05,sum(main$c1), "BaseLine") returns character vector.

Try:

df <- data.frame("coeff" = numeric(), "value" = numeric(), "Type" = character(), stringsAsFactors = FALSE)
df <- rbind.data.frame(df,cbind.data.frame(0.05, 100, "BaseLine", stringsAsFactors = FALSE), stringsAsFactors = FALSE )
> str(df)
'data.frame':   1 obs. of  3 variables:
 $ 0.05      : num 0.05
 $ 100       : num 100
 $ "BaseLine": chr "BaseLine"

Upvotes: 1

Related Questions