2

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.

anup
  • 465
  • 3
  • 18
  • what you want is a function which converts any column with characters into `as.character` and any column with numerals into `as.numeric` right? – Rana Usman Apr 18 '18 at 10:57
  • @RanaUsman yes.. but avoiding the use of manual functions to reduce time lag – anup Apr 18 '18 at 15:38

1 Answers1

1

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"
pieca
  • 2,463
  • 1
  • 16
  • 34
  • Yes. This looks great. But this gives rise to another problem. Try running the second line of code another time, with values "0.1", "100","BaseLine". Of course I can always use this code after first rbind `colnames(df) <- c("coeff","value","Type") ` and then `df <- rbind.data.frame(df,cbind.data.frame(coeff = 0.1, value = 100, Type = "BaseLine", stringsAsFactors = FALSE), stringsAsFactors = FALSE )` But is there a solution to preserving col names as well ? – anup Apr 18 '18 at 15:49
  • The only solution I came across are similar to this : https://stackoverflow.com/questions/5231540/r-losing-column-names-when-adding-rows-to-an-empty-data-frame/41609844 – anup Apr 18 '18 at 15:52