unwanted conversion to character

I create a list of dataframes with one column as character vector. But when I enclose those inside a list, all the columns get converted into character which I don't want. What is happening here?

A MWE is provided below

## Unwanted conversion to character
library(tidyverse)
df_fn_new<-function(n){
  df<-data.frame(sample(n),sample(LETTERS,n),as.character(sample(50:100,n)))
}

df_new_list<-1:4 %>% map(~df_fn_new(5))
map(df_new_list,~apply(.x,2,is.numeric))

When I run your example, none of the columns are character.

All the columns are false for is.numeric(). It should be false only for 2nd and 3rd column right?

The columns are integer,factor,factor - all correct. You did not specify any numeric columns. as.data.frame converts all text to factors unless you specify stringsAsFactors = FALSE

I think I see where you are confused. You are not applying is.numeric where you think you are. Try this:

df_new_list[[1]][[1]]
is.numeric(df_new_list[[1]][[1]])

You need to extract the object (the column) in order to see what it is.

This is not true at all.

First of all, an integer is a number as well, so it should be true. Second, the default has been changed since version 4, and R do not convert characters to factors by default any more.

@nithinmkp The reason you are getting this result is because of coercion to matrix, which converts everything to same type. This is result of using apply. Please use lapply, or even map would do the job.

map(df_new_list,~map(.x,is.numeric))

Hope this helps.

Yes. So the numeric column was not character. Just that suing apply returns character right? when i used map_lgl I got the desired output.

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