Data frame typecasting entire column to character from numeric

谁说胖子不能爱 提交于 2019-12-02 04:36:32

Short answer is you cannot.
As was mentioned in the comments, in a data frame, all elements of a column must have the same mode.

If you would like to specifically find the values that are "number like" you can use the following (where vec here would be, say, a data frame column)

  vec[!is.na(as.numeric((vec)))]

You can then convert these, but unfortunately you cannot put the converted values back into the same column. As as you do, they will be coerced back to character



As for a function that can convert the whole dataframe to numeric (realizing that isolating specific entries as exceptions is not possible), you can use sapply

  sapply(dataFrameName, as.numeric)

You are allowed to have vectors of type list in a data.frame, and the list can contain any type of object except functions as long as it is of the same length as the other columns in the data.frame, e.g.:

mydataframe <- data.frame(numbers=1:3)
mydataframe$mylist <- list(1, 'plum', 5)
mydataframe
#  numbers mylist
#1       1      1
#2       2   plum
#3       3      5
sapply(mydataframe, typeof)
#  numbers    mylist 
#"integer"    "list" 
sapply(mydataframe$mylist, typeof)
#[1] "double"    "character" "double"  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!