如何添加 NA 值以从不同长度的向量创建数据矩阵?
How do I add NA values to create a data matrix from vectors of differing length?
I 运行 数据框上的应用函数,以提取值 >-1 的所有单元格的位置。但是,在我的结果中,每列中的单元格数量不同,因此 R 不允许我将结果转换为数据框。
我的原始数据框示例(实际有 500 多列):
Slopes<-data.frame(B1=5:495,B2=-100:390, B3=10:500,B4=-200:290)
row.names(Slopes)<-seq(0.01, 4.91, 0.01)
这是我 运行 对向量的函数:
Z<-apply(Slopes, 2, function(x) which(x>-1))
如何用 "NA" 填充缺失的单元格,以便将这些结果转换为数据框?
我还必须添加此编辑,因为现在我已经成功制作了数据框,我发现 R return 编辑了行号而不是行名。我可以对我的应用代码进行任何更改,这将 return 行名称改为?
试试这个:
Z <- apply(Slopes, 2, function(x) which(x>-1))
str(Z)
# Length of longest sub-list
max(rapply(Z, length))
## 491
matrix_Z <- sapply(Z,'[',1:491)
tail(matrix_Z)
## B1 B2 B3 B4
##4.86 486 NA 486 NA
##4.87 487 NA 487 NA
##4.88 488 NA 488 NA
##4.89 489 NA 489 NA
##4.9 490 NA 490 NA
##4.91 491 NA 491 NA
从您的 Z
开始,您可以使用以下内容:
data.frame(lapply(Z, "length<-", max(lengths(Z))))
输出如下:
> head(data.frame(lapply(Z, "length<-", max(lengths(Z)))))
B1 B2 B3 B4
0.01 1 101 1 201
0.02 2 102 2 202
0.03 3 103 3 203
0.04 4 104 4 204
0.05 5 105 5 205
0.06 6 106 6 206
> tail(data.frame(lapply(Z, "length<-", max(lengths(Z)))))
B1 B2 B3 B4
4.86 486 NA 486 NA
4.87 487 NA 487 NA
4.88 488 NA 488 NA
4.89 489 NA 489 NA
4.9 490 NA 490 NA
4.91 491 NA 491 NA
要获得 rownames
,只需按如下方式更改 "Z":
Z <- apply(Slopes, 2, function(x) rownames(Slopes)[which(x>-1)])
I 运行 数据框上的应用函数,以提取值 >-1 的所有单元格的位置。但是,在我的结果中,每列中的单元格数量不同,因此 R 不允许我将结果转换为数据框。
我的原始数据框示例(实际有 500 多列):
Slopes<-data.frame(B1=5:495,B2=-100:390, B3=10:500,B4=-200:290)
row.names(Slopes)<-seq(0.01, 4.91, 0.01)
这是我 运行 对向量的函数:
Z<-apply(Slopes, 2, function(x) which(x>-1))
如何用 "NA" 填充缺失的单元格,以便将这些结果转换为数据框?
我还必须添加此编辑,因为现在我已经成功制作了数据框,我发现 R return 编辑了行号而不是行名。我可以对我的应用代码进行任何更改,这将 return 行名称改为?
试试这个:
Z <- apply(Slopes, 2, function(x) which(x>-1))
str(Z)
# Length of longest sub-list
max(rapply(Z, length))
## 491
matrix_Z <- sapply(Z,'[',1:491)
tail(matrix_Z)
## B1 B2 B3 B4
##4.86 486 NA 486 NA
##4.87 487 NA 487 NA
##4.88 488 NA 488 NA
##4.89 489 NA 489 NA
##4.9 490 NA 490 NA
##4.91 491 NA 491 NA
从您的 Z
开始,您可以使用以下内容:
data.frame(lapply(Z, "length<-", max(lengths(Z))))
输出如下:
> head(data.frame(lapply(Z, "length<-", max(lengths(Z)))))
B1 B2 B3 B4
0.01 1 101 1 201
0.02 2 102 2 202
0.03 3 103 3 203
0.04 4 104 4 204
0.05 5 105 5 205
0.06 6 106 6 206
> tail(data.frame(lapply(Z, "length<-", max(lengths(Z)))))
B1 B2 B3 B4
4.86 486 NA 486 NA
4.87 487 NA 487 NA
4.88 488 NA 488 NA
4.89 489 NA 489 NA
4.9 490 NA 490 NA
4.91 491 NA 491 NA
要获得 rownames
,只需按如下方式更改 "Z":
Z <- apply(Slopes, 2, function(x) rownames(Slopes)[which(x>-1)])