我想收集class
中某些列的data_frame
。所以:
df_x = data_frame(date1 = seq.POSIXt(from = as.POSIXct("2016-01-01 12:00:00 UTC"),
to = as.POSIXct("2016-01-03 12:00:00 UTC"), by = "hour",
tz = "UTC"),
date2 = seq.POSIXt(from = as.POSIXct("2016-01-01 12:00:00 UTC"),
to = as.POSIXct("2016-01-03 12:00:00 UTC"), by = "hour",
tz = "UTC"))
class(df_x$date1)
class(df_x$date2)
如何针对一堆列收集调用class
的结果?我可以限制返回向量的第一个元素,然后调用summarize_each
有效:
# summarize_each
get_class = function(x) class(x)[1]
df_x %>%
summarise_each(funs(get_class), date1, date2)
我想知道如何为data_frame
中的一堆变量获取任意列data_frame
的最大类数的变量?我的猜测是,调用do
和某些后处理的某种组合可以在这里工作。
期望的结果:
# desired result
df_result = data_frame(date1 = c("POSIXct", "POSIXt"),
date2 = c("POSIXct", "POSIXt"))
> df_result
Source: local data frame [2 x 2]
date1 date2
(chr) (chr)
1 POSIXct POSIXct
2 POSIXt POSIXt
答案 0 :(得分:0)
我没有使用dplyr
所以只坚持base
:
df_x <- data.frame(date1 = seq.POSIXt(from = as.POSIXct("2016-01-01 12:00:00 UTC"),
to = as.POSIXct("2016-01-03 12:00:00 UTC"), by = "hour",
tz = "UTC"),
date2 = seq.POSIXt(from = as.POSIXct("2016-01-01 12:00:00 UTC"),
to = as.POSIXct("2016-01-03 12:00:00 UTC"), by = "hour",
tz = "UTC"),
character1 = sample(LETTERS, 49, replace = TRUE),
numeric1 = sample(1:100, 49, replace = TRUE))
df_x.class <- lapply(df_x, class)
cbind.fill <- function(n) {
vec.len <- max(unlist(lapply(n, length)))
list.appended <- lapply(n, function(m) {
if(length(m) < vec.len) {
vec.append <- vec.len - length(m)
m <- c(m, rep(NA, vec.append))}
m})
do.call(cbind, list.appended)}
cbind.fill(df_x.class)
答案 1 :(得分:0)
我会用你的例子尝试下面的单行代码:
as.data.frame(lapply(df_x, class))