简体   繁体   中英

R: converting some levels of a factor to numeric

I am new to R. I have a factor object with >10000 levels. Most of these levels are numbers which I would like to convert to numeric, but there are several levels that contain descriptions which I do not wish to touch.

Is there a good way for me to isolate the relevant levels of the factor to convert into numeric? Would as.numeric() be a good choice?

Many thanks!

As we cannot have a column/vector with multiple class, one suggestion is to subset only the numeric elements and convert it back to numeric using as.numeric(as.character(

i1 <- grepl("^[0-9.]+$", v1)
v2 <- as.numeric(as.character(v1[i1]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM