R语言 不同行数的列/不同长度向量/不同长度列表 合并为dataframe

不同长度向量合并为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"


版权声明:本文为CSDN博主「AdaWong_Corner」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/ada0915/article/details/82849836

你可能感兴趣的:(python,R语言,基础/画图等,r语言)