itj*_*s18 3 r vector dataframe
我有不同长度的矢量.例如:
df1
[1] 1 95 5 2 135 4 3 135 4 4 135 4 5 135 4 6 135 4
df2
[1] 1 70 3 2 110 4 3 112 4
Run Code Online (Sandbox Code Playgroud)
我正在尝试在R中编写一个脚本,以便让任何向量进入函数或for循环,它返回一个三列的数据帧.因此,每个输入向量的单独数据帧.每个向量是三的倍数(因此,三列).在编写函数方面我对R很新,似乎无法解决这个问题.这是我的尝试:
newdf = c()
ld <- length(df1)
ld_mult <- length(df1)/3
ld_seq <- seq(from=1,to=ld,by=3)
ld_seq2 < ld_seq +2
for (i in 1:ld_mult) {
newdf[i,] <- df1[ld_seq[i]:ld_seq2[i]]
}
Run Code Online (Sandbox Code Playgroud)
我想要的输出df1将是:
1 95 5
2 135 4
3 135 4
4 135 4
5 135 4
6 135 4
Run Code Online (Sandbox Code Playgroud)
这是一个如何matrix用于此目的的示例:
x <- c(1, 95, 5,2, 135, 4, 3, 135, 4)
as.data.frame(matrix(x, ncol = 3, byrow = TRUE))
# V1 V2 V3
#1 1 95 5
#2 2 135 4
#3 3 135 4
Run Code Online (Sandbox Code Playgroud)
和
y <- c(1, 70, 3, 2, 110, 4, 3, 112, 4)
as.data.frame(matrix(y, ncol = 3, byrow = TRUE))
# V1 V2 V3
#1 1 70 3
#2 2 110 4
#3 3 112 4
Run Code Online (Sandbox Code Playgroud)
或者,如果您想使其成为自定义功能:
newdf <- function(vec) {
as.data.frame(matrix(vec, ncol = 3, byrow = TRUE))
}
newdf(y)
#V1 V2 V3
#1 1 70 3
#2 2 110 4
#3 3 112 4
Run Code Online (Sandbox Code Playgroud)
如果向newdf添加另一个参数,您还可以让用户使用该函数指定他想要创建的列数:
newdf <- function(vec, cols = 3) {
as.data.frame(matrix(vec, ncol = cols, byrow = T))
}
Run Code Online (Sandbox Code Playgroud)
现在,如果用户没有指定数字,则默认列数为3.如果他愿意,他可以像这样使用它:
newdf(z, 5) # to create 5 columns
Run Code Online (Sandbox Code Playgroud)
该函数的另一个不错的小插件是检查输入向量长度是否是函数调用中指定的列数的倍数:
newdf <- function(vec, cols = 3) {
if(length(vec) %% cols != 0) {
stop("Number of columns is not a multiple of input vector length. Please double check.")
}
as.data.frame(matrix(vec, ncol = cols, byrow = T))
}
newdf(x, 4)
#Error in newdf(x, 4) :
# Number of columns is not a multiple of input vector length. Please double check.
Run Code Online (Sandbox Code Playgroud)
如果你有多个向量坐在一个list,这里是你如何将它们转换为data.frame:
> l <- list(x,y)
> l
#[[1]]
#[1] 1 95 5 2 135 4 3 135 4
#
#[[2]]
#[1] 1 70 3 2 110 4 3 112 4
> lapply(l, newdf)
#[[1]]
# V1 V2 V3
#1 1 70 3
#2 2 110 4
#3 3 112 4
#
#[[2]]
# V1 V2 V3
#1 1 70 3
#2 2 110 4
#3 3 112 4
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
514 次 |
| 最近记录: |