简体   繁体   中英

Manipulating a character vector by considering a grouping Q-matrix in r (1)

I am trying to write code based on a Group variable, item.map that has item information that includes an q-matrix showing which item is associated with which group.

Group <- c(1,2)
item.map <- data.frame(
  item.id = c(21,41,61,72),
  group.1 = c(1,1,1,0),
  group.2 = c(0,1,0,1)
)

> item.map
  item.id group.1 group.2
1      21       1       0
2      41       1       1
3      61       1       0
4      72       0       1

In this item.map group.1 had 3 items while group.2 has two items. Using this item.map I wanted to assign those items within the chunk of code below but I was not able to plug the item.map information.

OUTPUT <- as.data.frame(c())
for(j in 1:length(Group)) {
  
  output <- c(paste0("Group G",unique(Group)[j],":"),
             paste0("Items = ",paste0(item.map$item.id, collapse=", "), ";"), #Items
             paste0(paste0("Codes(", item.map$item.id, ") = 0(0), 1(1)",collapse="; ", sep=""),";"), #Codes
             paste0(paste("Model(", item.map$item.id, ") = 2PL",collapse="; ", sep=""),";"))
  
  
  OUTPUT <- c(OUTPUT, output)
  
}

> OUTPUT
[1] "Group G1:"
[1] "Items = 21, 41, 61, 72;"
[1] "Codes(21) = 0(0), 1(1); Codes(41) = 0(0), 1(1); Codes(61) = 0(0), 1(1); Codes(72) = 0(0), 1(1);"
[1] "Model(21) = 2PL; Model(41) = 2PL; Model(61) = 2PL; Model(72) = 2PL;"

[1] "Group G2:"
[1] "Items = 21, 41, 61, 72;"
[1] "Codes(21) = 0(0), 1(1); Codes(41) = 0(0), 1(1); Codes(61) = 0(0), 1(1); Codes(72) = 0(0), 1(1);"
[1] "Model(21) = 2PL; Model(41) = 2PL; Model(61) = 2PL; Model(72) = 2PL;"

So, in the desired output, Group 1 should not have item 72 and Group 2 should not have items 21 and 61 information in the grouping chunk.

The desired output is:
    > OUTPUT
    [1] "Group G1:"
    [1] "Items = 21, 41, 61;"
    [1] "Codes(21) = 0(0), 1(1); Codes(41) = 0(0), 1(1); Codes(61) = 0(0), 1(1);"
    [1] "Model(21) = 2PL; Model(41) = 2PL; Model(61) = 2PL;"
    
    [1] "Group G2:"
    [1] "Items = 41, 72;"
    [1] "Codes(41) = 0(0), 1(1); Codes(72) = 0(0), 1(1);"
    [1] "Model(41) = 2PL; Model(72) = 2PL;"

Does anyone have any ideas? Thanks

Here, we need to do the subset based on the 'group' columns (added as.logical(item.map[[paste0("group.", j)]]) )

OUTPUT <- c()
for(j in 1:length(Group)) {
  tmp <- item.map$item.id[as.logical(item.map[[paste0("group.", j)]])]
  output <- c(paste0("Group G",unique(Group)[j],":"),
     paste0("Items = ",
       paste0(tmp, collapse=", "), ";"), #Items
        paste0(paste0("Codes(", tmp, ") = 0(0), 1(1)",
                 collapse="; ", sep=""),";"), #Codes
        paste0(paste("Model(", tmp, ") = 2PL",collapse="; ", sep=""),";"))
  
  
  OUTPUT <- c(OUTPUT, output)
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM