Alex
Alex

Reputation: 41

How can I combine a number of columns value together using loop condition in R

Now I have a matrix like below and I cannot access specific column but to use matrixname[,3] to access

       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    8    2   10    9   NA   NA   NA   NA   NA    NA
[2,]   10    2    8   NA   NA   NA   NA   NA   NA    NA
[3,]    8    6    9   NA   NA   NA   NA   NA   NA    NA
[4,]    1    3   10    8   NA   NA   NA   NA   NA    NA
[5,]    4    6    9   NA   NA   NA   NA   NA   NA    NA
[6,]    8    2   10    9   NA   NA   NA   NA   NA    NA
[7,]    1    8    3   NA   NA   NA   NA   NA   NA    NA
[8,]    2    6    4   NA   NA   NA   NA   NA   NA    NA

I'm using a loop when the i value of the loop is 2, I need to merge the column one and column two value like 8,2 10,2. When my loop i is 3, I will have to merge column 1 to column 3 like 8,2,10.

Or is there any better way to merge the column value easily? Later I need to compare the merge value 8,2 with another matrix to check whether it exist or not.

I have another matrix like this formed using

df1 <- cSplit(data.frame(a = gsub('<-', '', trans$V1)), 'a', ' ','wide') aw <- cbind(df1, rules[,-1])

     a_1 a_2 a_3 V2       V3
 1:  10   8   3  7 0.318182
 2:   3   8  10  7 0.437500
 3:   8   3  10  7 1.000000
 4:   3   8  NA 22 0.448980
 5:   8   3  NA 22 0.846154
 6:   9   8  10  7 0.437500

I use subset(aw,is.na(a_3)) to remove row that are NA, then I want to merge a_2 and a_3 using loop as well because I might have a_4 or a_5. Expected Ouput:

    a_1  a_2,a_3  V2       V3
 1:  10   8,3     7 0.318182
 2:   3   8,10    7 0.437500
 3:   8   3,10    7 1.000000
 4:   3   8,NA   22 0.448980
 5:   8   3,NA   22 0.846154
 6:   9   8,10    7 0.437500

Upvotes: 0

Views: 190

Answers (1)

akrun
akrun

Reputation: 886948

We can either use a for loop (in that case, create an object to store the output) or use one of the apply family functions i.e. sapply/lapply. Loop over the sequence of columns in this case, we are using only the first 3 columns. subset the matrix, paste the rows and assign the output to the 'lst' already created.

lst <- vector("list", 3);
for(i in seq_along(lst)){
 lst[[i]] <- do.call(paste, 
      c(as.data.frame(m1[, 1:i, drop=FALSE]), list(sep=",")))
}

lst
#[[1]]
#[1] "8"  "10" "8"  "1"  "4"  "8"  "1"  "2" 

#[[2]]
#[1] "8,2"  "10,2" "8,6"  "1,3"  "4,6"  "8,2"  "1,8"  "2,6" 

#[[3]]
#[1] "8,2,10" "10,2,8" "8,6,9"  "1,3,10" "4,6,9"  "8,2,10" "1,8,3"  "2,6,4" 

If we need it as a matrix, either rbind or cbind the output of the list

do.call(cbind, lst)

Upvotes: 2

Related Questions