在r中将多列从字符转换为数字格式 [英] converting multiple columns from character to numeric format in r

查看:23
本文介绍了在r中将多列从字符转换为数字格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将数据框中的多列从字符格式转换为数字格式的最有效方法是什么?

What is the most efficient way to convert multiple columns in a data frame from character to numeric format?

我有一个名为 DF 的数据框,其中包含所有字符变量.

I have a dataframe called DF with all character variables.

我想做类似的事情

for (i in names(DF){
    DF$i <- as.numeric(DF$i)
}

谢谢

推荐答案

你可以试试

DF <- data.frame("a" = as.character(0:5),
                 "b" = paste(0:5, ".1", sep = ""),
                 "c" = letters[1:6],
                 stringsAsFactors = FALSE)

# Check columns classes
sapply(DF, class)

#           a           b           c 
# "character" "character" "character" 

cols.num <- c("a","b")
DF[cols.num] <- sapply(DF[cols.num],as.numeric)
sapply(DF, class)

#          a           b           c 
#  "numeric"   "numeric" "character"

这篇关于在r中将多列从字符转换为数字格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆