Results of as_numeric are not as expected

I have a dataframe with this :

structure(list(name = c("Andres", "Angel", "Aleop", "Kevin", "Thomas", "Aleez", 
"Andoz", "Antonio", "Javi", "Pol"), 
    conv = c("19", "18", "1", "18", "16", "16", "17", "17", 
    "12", "1"), play = c("18", "1", "0", "17", "16", "13", 
    "16", "15", "9", "1"),goal = c("-", "-", "0", "1", "-", "1", 
    "-", "1", "2", "-"), mins = c("1.620", "90", NA,  "1.505", "1.335", "623", "1.124", "1.227", 
    "796", "1")), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"))

When I try to convert the mins column to numeric with df$mins <- as.numeric(df$mins) the result I get is not correct. I get 1.620, 90.000, NA, 1.505, 1.335, 623.000, 1.124, 1.227, 796.000, 1.000 when what I want is the original sequence but in numeric format.

What you get is correct. Are you saying that you want to see 90 rather than 90.000? That is a function of how you print the results.

Yes @prubin , I want to obtain 90 not 90.000. How can I achieve this?

First, note that when you execute View(df) you see "90.000" but if you execute df[2, "mins"] you see "90". As I said, what you see is a function of how you generate the output. If you are printing the contents of df, you could try something like the following (which creates a variable m containing the value of mins in row i of df):

for (i in 1:nrow(df)) {
  x  <-  df[i, "mins"]
  m <- ifelse(round(x) == x, as.integer(x), x)
  print(m)
}

I think that a data frame column can be numeric or integer but it can't store both kinds of values.

df <- data.frame(mins = c(1, 2.3))
str(df) #mins column is numeric
#> 'data.frame':    2 obs. of  1 variable:
#>  $ mins: num  1 2.3

for (i in 1:nrow(df)) {
  x  <-  df[i, "mins"]
  df[i, "mins"] <- ifelse(round(x) == x, as.integer(x), x)
}
str(df) #still numeric
#> 'data.frame':    2 obs. of  1 variable:
#>  $ mins: num  1 2.3

df$mins <- as.integer(df$mins) #force everything to integer
str(df) 
#> 'data.frame':    2 obs. of  1 variable:
#>  $ mins: int  1 2

Created on 2024-01-07 with reprex v2.0.2

1 Like

This topic was automatically closed 42 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.