如何使用for循环使用R分割矩阵或数据帧?
我想使用for loop函数输出n/2 NewMatrix,NewMatrix这可能有帮助:如何使用for循环使用R分割矩阵或数据帧?,r,matrix,split,dataframe,R,Matrix,Split,Dataframe,我想使用for loop函数输出n/2 NewMatrix,NewMatrix这可能有帮助: indx <- 1:(ncol(OldMatrix)-1) lst1 <- setNames(lapply(indx, function(i) OldMatrix[,c(i, i+1)]), paste("NewMatrix",indx, sep="_")) lst1$NewMatrix_10 # J K #[1,] "1" "4" #[2,] "1" "4
indx <- 1:(ncol(OldMatrix)-1)
lst1 <- setNames(lapply(indx, function(i) OldMatrix[,c(i, i+1)]), paste("NewMatrix",indx, sep="_"))
lst1$NewMatrix_10
# J K
#[1,] "1" "4"
#[2,] "1" "4"
#[3,] "1" "4"
#[4,] "1" "4"
#[5,] "1" "4"
#[6,] "1" "4"
indx您应该使用列表。每当您有名为x_1
,x_2
,….的变量时,这就很好地表明,使用名为x
的列表以及元素1
,2
。。。
indx <- 1:(ncol(OldMatrix)-1)
lst1 <- setNames(lapply(indx, function(i) OldMatrix[,c(i, i+1)]), paste("NewMatrix",indx, sep="_"))
lst1$NewMatrix_10
# J K
#[1,] "1" "4"
#[2,] "1" "4"
#[3,] "1" "4"
#[4,] "1" "4"
#[5,] "1" "4"
#[6,] "1" "4"