我有以下矩阵:
Type Tenor Frequency Rate
[1,] "SWAP" "1" "1" "-0.0048"
[2,] "SWAP" "2" "1" "-0.00334"
[3,] "SWAP" "3" "1" "-0.00221"
[4,] "SWAP" "4" "1" "-0.00135"
[5,] "SWAP" "5" "1" "-0.00051"
[6,] "SWAP" "6" "1" "0.00022"
[7,] "SWAP" "7" "1" "9e-04"
[8,] "SWAP" "8" "1" "0.00156"
[9,] "SWAP" "9" "1" "0.002155"
[10,] "SWAP" "10" "1" "0.002787"
但我需要对其中一些值进行二进制操作,因此需要将列"Tenor“、"Frequency”和"Rate“转换为数字。
我试着使用这个函数: apply(input_matrix,2,as.numeric),它给了我这样的结果:
Type Tenor Frequency Rate
[1,] NA 1 1 -0.004800
[2,] NA 2 1 -0.003340
[3,] NA 3 1 -0.002210
[4,] NA 4 1 -0.001350
[5,] NA 5 1 -0.000510
[6,] NA 6 1 0.000220
[7,] NA 7 1 0.000900
[8,] NA 8 1 0.001560
[9,] NA 9 1 0.002155
[10,] NA 10 1 0.002787
但只要我用for循环在第一列中插入一个字符串:
for(row in 1:nrow(input_matrix)) {
input_matrix[row, 1] <- "SWAP";
}
它将矩阵中的所有值转换回字符串:
Type Tenor Frequency Rate
[1,] "SWAP" "1" "1" "-0.0048"
[2,] "SWAP" "2" "1" "-0.00334"
[3,] "SWAP" "3" "1" "-0.00221"
[4,] "SWAP" "4" "1" "-0.00135"
[5,] "SWAP" "5" "1" "-0.00051"
[6,] "SWAP" "6" "1" "0.00022"
[7,] "SWAP" "7" "1" "9e-04"
[8,] "SWAP" "8" "1" "0.00156"
[9,] "SWAP" "9" "1" "0.002155"
[10,] "SWAP" "10" "1" "0.002787"
所以我不能在上面做手术。
如何仅将特定列转换为数字列?
我也尝试过apply(input_matrix[,2:4], 2, as.numeric)
,但它只返回最后3列。
额外的问题:为什么它会有这样的效果(将矩阵中的所有值转换回字符串)?
发布于 2021-11-17 06:42:10
感谢您的评论@caldwellst,我了解到矩阵中不可能有不同的类型,但我可以将矩阵转换为数据帧。
所以我用和以前完全一样的方法创建了我的矩阵,但是我没有在第一列中放入任何值,所以我得到了:
Type Tenor Frequency Rate
[1,] NA 1 1 -0.00480
[2,] NA 2 1 -0.00334
[3,] NA 3 1 -0.00221
[4,] NA 4 1 -0.00135
[5,] NA 5 1 -0.00051
[6,] NA 6 1 0.00022
然后使用input_df = as.data.frame(input_matrix)
将其转换为数据帧,然后才将字符串插入到第一列中:
for(row in 1:nrow(input_df)) {
input_df[row, 1] <- "SWAP";
}
现在,我有了最后3列中包含数字的数据帧:
Type Tenor Frequency Rate
1 SWAP 1 1 -0.00480
2 SWAP 2 1 -0.00334
3 SWAP 3 1 -0.00221
4 SWAP 4 1 -0.00135
5 SWAP 5 1 -0.00051
6 SWAP 6 1 0.00022
https://stackoverflow.com/questions/70006040
复制相似问题