Turn Specific Rows of Dataframe into Numeric Mode?

Hi there,

Does anyone know of a way to turn specific rows in a dataframe from a character mode to a numeric mode?

The first row in my dataframe I want to be a character vector of units. The rest of the rows I want to be numeric. Here's something I tried, even though I had a feeling it wouldn't work:

avg[2:6,] <- as.numeric(avg[2:6,])

Any ideas? Here's a subset of my data:

avg <- structure(list(Depth_interval = c("m", "(0,1]", "(1,2]", "(2,3]", 
"(3,4]", "(4,5]"), Avg_Green.Algae = c("µg/l", "2.842", "5.5", 
"5.42", "4.698", "4.162"), Avg_Bluegreen = c("µg/l", "0.03", 
"0", "0", "0", "0"), Avg_Diatoms = c("µg/l", "7.546", "14.04", 
"13.45", "13.53", "13.486"), Avg_Cryptophyta = c("µg/l", "0", 
"0", "0", "0", "0"), Avg_Yellow.substances = c("r.u.", "1.41", 
"2.46666666666667", "2.3175", "2.482", "2.514"), Avg_Total.conc = c("µg/l", 
"10.418", "19.5366666666667", "18.8725", "18.228", "17.65"), 
    Avg_Transmission = c("%", "87.026", "95.78", "96.03", "96.19", 
    "96.248"), Avg_Depth = c("m", "0.26", "1.48", "2.355", "3.42", 
    "4.592"), Avg_Temperature = c("¡C", "19.298", "19.3066666666667", 
    "19.1425", "18.576", "17.9")), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))

Thanks so much!

data.frames are required to have columns of singular types. (there is a weird exception when you have them be a list type but this wont give you the presentation you wish for).
Best advice is while you are working with a data.frame for computation, have it fully numeric as you need. Presentation is a different task than calculation. When it comes to presentation, you can cast all numbers to characters ,and manipulate the data.frame for printing arbitrarily to achieve any desired effect.

If you want a final printable dataframe with units on the first row, cast everything as character (but recognise that your data.frame is no longer optimal for computing with, only presenting with).

1 Like

Thanks so much for the explanation! That makes sense that columns have to be singular types for computational purposes. Appreciate it!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.