R 如何使用函数为具有类似结构的数据帧设置列类?

R 如何使用函数为具有类似结构的数据帧设置列类?,r,R,我有多个具有相同或相似列的数据帧。如何使用函数为每个变量设置变量类,而不必手动更改每个名称 library(lubridate) color <- c("red", "blue", "green") weight <- c("10","5","10") launch_date <- c("2017-10-01", "2017-11-01", "2017-10-02") df <- data.frame(color, weight, launch_date) df$co

我有多个具有相同或相似列的数据帧。如何使用函数为每个变量设置变量类,而不必手动更改每个名称

library(lubridate)

color <- c("red", "blue", "green")
weight <- c("10","5","10")
launch_date <- c("2017-10-01", "2017-11-01", "2017-10-02")
df <- data.frame(color, weight, launch_date)

df$color <- as.character(df$color)
df$weight <- as.numeric(df$weight)
df$launch_date <- ymd(df$launch_date)
库(lubridate)

color
readr::type\u convert
可以执行以下操作:

df$color:chr“红色”“蓝色”“绿色”
#>$weight:int 10 5 10
#>$launch_日期:日期,格式:“2017-10-01”“2017-11-01”。。。

utils::type.convert也存在,但它只对单个向量有效,不会处理日期和日期时间。

谢谢,但我不确定这是否能帮助我在只键入一次数据帧名称的情况下更改函数中的所有类。这是您的函数。它会自动计算出列类型。如果要手动设置它们,请设置其
col_types
参数。我对原始问题进行了编辑,以便更具体地说明只想键入一次df的名称。使用
readr::type_convert()
只需键入一次数据集的名称。我很难理解为什么这里不需要
type\u convert
。很可能我误解了,但是如果我有两个df,df1和df2,我不需要键入:df1吗
class_set_fun <- function(x){
 x$color <- as.character(x$color)
 x$weight <- as.numeric(x$weight)
 x$launch_date <- ymd(x$launch_date)
}

class_set_fun(df2)