gpt4 book ai didi

r - 如何将向量转换为具有固定维数的数据帧

转载 作者:行者123 更新时间:2023-12-04 04:56:58 25 4
gpt4 key购买 nike

我有长度为四的倍数的列表向量:

mylist <- c("1", "darkorange", "16876", "16890", "2", "pink", "6833", "7189", 
"2", "pink", "9181", "9279", "2", "darkgreen", "1846", "2170"
)

我想做的就是将那个列表变成一个数据框
尺寸(M * 4):
V1    V2           V3     V4
"1" "darkorange" "16876" "16890"
"2" "pink" "6833" "7189"
"2" "pink" "9181" "9279"
"2" "darkgreen" "1846" "2170"

我该如何实现?

最佳答案

只需转换为matrix,指定ncol

m1 <- matrix(mylist, ncol=4, byrow=TRUE)
d1 <- as.data.frame(m1, stringsAsFactors=FALSE)
d1
# V1 V2 V3 V4
#1 1 darkorange 16876 16890
#2 2 pink 6833 7189
#3 2 pink 9181 9279
#4 2 darkgreen 1846 2170

“data.frame”列均为 character类,因为输入的 vectorcharacter。我们可以使用 class根据数字/非数字值转换 type.convert
d1[] <- lapply(d1, type.convert)
str(d1)
#'data.frame': 4 obs. of 4 variables:
#$ V1: int 1 2 2 2
#$ V2: Factor w/ 3 levels "darkgreen","darkorange",..: 2 3 3 1
#$ V3: int 16876 6833 9181 1846
#$ V4: int 16890 7189 9279 2170

关于r - 如何将向量转换为具有固定维数的数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32173557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com