简体   繁体   中英

coerce a list object to type double

This question has been asked many times, but the suggested solutions somehow do not work for me.

d <- data.frame(var1 = c("ab","ac", "ad"), var2 = c("1.1","2.6","0"),var3 = c("1","5.4","0"))

ff <- as.numeric(as.character(d[ ,2:3]))
fg <- lapply(d[ ,2:3],as.numeric)
fh <- as.numeric(unlist(d[ ,2:3]))
fi <- as.numeric(d[ ,2:3])

var2 and var3 are classified as factors. I do not want to rearrange or merge columns or cells. I just want them to be numeric in order to be able to calculate.

To apply the coercion on a subset of multiple columns, lapply is the right way. That yields a list, that you want to assign back to the subset columns.

as.numeric.factor <- function(f) as.numeric(levels(f))[f]    
# as.numeric.factor <- function(f) as.numeric(as.character(f))  ## alternatively

d[,2:3] <- lapply(d[,2:3], as.numeric.factor)

str(d)
# 'data.frame': 3 obs. of  3 variables:
# $ var1: chr  "ab" "ac" "ad"
# $ var2: num  1.1 2.6 0
# $ var3: num  1 5.4 0

If you want a new object you may use the lapply with replace .

fg <- replace(d, 2:3, lapply(d[,2:3], as.numeric.factor))
str(fg)
# 'data.frame': 3 obs. of  3 variables:
# $ var1: chr  "ab" "ac" "ad"
# $ var2: num  1.1 2.6 0
# $ var3: num  1 5.4 0

Data

d <- structure(list(var1 = c("ab", "ac", "ad"), var2 = structure(c(2L, 
3L, 1L), .Label = c("0", "1.1", "2.6"), class = "factor"), var3 = structure(c(2L, 
3L, 1L), .Label = c("0", "1", "5.4"), class = "factor")), row.names = c(NA, 
-3L), class = "data.frame")

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