安利好朋友写的美食文牛排到底要点几分熟,我觉得写得真不错 ,有兴趣的朋友们可以点开看看哟!
不同长度向量合并为data.frame
># 构造列表
> (a_list = list(
+ c(1, 1, 2, 5, 14, 42),
+ month.abb,
+ c(1, 1, 2, 5, 14, 42, 22,88, 0)))
# [[1]]
# [1] 1 1 2 5 14 42
#
# [[2]]
# [1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
#
# [[3]]
# [1] 1 1 2 5 14 42 22 88 0
>
> do.call(cbind, lapply(lapply(a_list, unlist), `length<-`, max(lengths(a_list))))
# [,1] [,2] [,3]
# [1,] "1" "Jan" "1"
# [2,] "1" "Feb" "1"
# [3,] "2" "Mar" "2"
# [4,] "5" "Apr" "5"
# [5,] "14" "May" "14"
# [6,] "42" "Jun" "42"
# [7,] NA "Jul" "22"
# [8,] NA "Aug" "88"
# [9,] NA "Sep" "0"
# [10,] NA "Oct" NA
# [11,] NA "Nov" NA
# [12,] NA "Dec" NA
>
> #当给合并后的data.frame每一列的命名时,则必须使用函数"cbind.data.frame"
> setNames(do.call(cbind.data.frame, lapply(lapply(a_list, unlist), `length<-`, max(lengths(a_list)))), paste0("V", 1:3))
# V1 V2 V3
# 1 1 Jan 1
# 2 1 Feb 1
# 3 2 Mar 2
# 4 5 Apr 5
# 5 14 May 14
# 6 42 Jun 42
# 7 NA Jul 22
# 8 NA Aug 88
# 9 NA Sep 0
# 10 NA Oct NA
# 11 NA Nov NA
# 12 NA Dec NA
>
> #当列表中的元素已被命名,则既可使用"cbind.data.frame",也可使用"cbind"
> names(a_list) = c("cat", "months", "dog")
> do.call(cbind, lapply(lapply(a_list, unlist), `length<-`, max(lengths(a_list))))
# cat months dog
# [1,] "1" "Jan" "1"
# [2,] "1" "Feb" "1"
# [3,] "2" "Mar" "2"
# [4,] "5" "Apr" "5"
# [5,] "14" "May" "14"
# [6,] "42" "Jun" "42"
# [7,] NA "Jul" "22"
# [8,] NA "Aug" "88"
# [9,] NA "Sep" "0"
# [10,] NA "Oct" NA
# [11,] NA "Nov" NA
# [12,] NA "Dec" NA
cbind 与cbind.data.frame 区别
> a <- 1:4
> b <- c("car", "bus", "train", "bike")
> ab <- cbind(a,b); ab
# a b
# [1,] "1" "car"
# [2,] "2" "bus"
# [3,] "3" "train"
# [4,] "4" "bike"
> class(ab)
# [1] "matrix"
> typeof(ab)
# [1] "character"
>
> ab <- cbind.data.frame(a,b); ab
# a b
# 1 1 car
# 2 2 bus
# 3 3 train
# 4 4 bike
> class(ab)
# [1] "data.frame"
> typeof(ab)
# [1] "list"
函数简单说明
setNames(object = nm, nm)
do.call(what, args, quote = FALSE, envir = parent.frame())
###do.call constructs and executes a function call from a name or a function and a list of arguments to be passed to it.
lapply(X, FUN, …)
###lapply returns a list of the same length as X, each element of which is the result of applying FUN to the corresponding element of X.