使用数据类型名称列表更改数据类型 [英] Change data types using a list of data type names

查看:82
本文介绍了使用数据类型名称列表更改数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从数据类型名称列表中更改数据框架列的数据类型的一种优雅方法是什么?

What is an elegant way to change the data types of data frames columns from a list of data type names?

这是一个示例(我正在寻找的是change_to_data_types函数):

Here's an example (change_to_data_types function is what I'm looking for):

my_df <- iris
my_types <- c("factor", "character", "double", "logical", "character")
my_df <- my_df %>% change_to_data_types(my_types)

my_types 的元素数与 my_df 中的列数相同,并且转换顺序相同.

my_types has the same number of elements as the number of columns in my_df and the conversion is done in the same order.

这是不礼貌"方式的示例

This is an example of an 'inelegant' way

my_df$Sepal.Length <- my_df$Sepal.Length %>% as.factor()
my_df$Sepal.Width <- my_df$Sepal.Width %>% as.character()
#etc...

推荐答案

一个选项是

library(tidyverse)
my_df[] <- map2(my_df, str_c("as.", my_types), ~ get(.y)(.x))


或在 base R

my_df[] <- Map(function(x, y) get(y)(x), my_df, paste0("as.", my_types))

-再次检查课程

sapply(my_df, class)
# Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
#    "factor"  "character"    "numeric"    "logical"  "character" 

这篇关于使用数据类型名称列表更改数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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