簡體   English   中英

r 操作序列的字符向量

[英]r manipulation a character vector for a sequence

我有一個問題 ID 列表,如下所示:

ids <- c("1_a","1_b","1_c","2_a","2_b","2_c","3_a","3_b","3_c")

ids開頭的1_,2_,3_代表分組(因子),所以共有9個問題有3個因子。 考慮到這個分組因子變量,我想生成一個字符變量,如下所示。

#for the first factor
(1_a, fixed[2]) = 0.0;
(1_a, fixed[3]) = 0.0;
(1_b, fixed[2]) = 0.0;
(1_b, fixed[3]) = 0.0;
(1_c, fixed[2]) = 0.0;
(1_c, fixed[3]) = 0.0;

#for the second factor
(2_a, fixed[1]) = 0.0;
(2_a, fixed[3]) = 0.0;
(2_b, fixed[1]) = 0.0;
(2_b, fixed[3]) = 0.0;
(2_c, fixed[1]) = 0.0;
(2_c, fixed[3]) = 0.0;

#for the third factor
(3_a, fixed[1]) = 0.0;
(3_a, fixed[2]) = 0.0;
(3_b, fixed[1]) = 0.0;
(3_b, fixed[2]) = 0.0;
(3_c, fixed[1]) = 0.0;
(3_c, fixed[2]) = 0.0;

所需的 output 背后的邏輯類似於因子分析。 當是第一個問題時,相同的問題系數對於其他因素是固定的。 例如,對於問題 1_a,我需要為第二個和第三個因素固定兩條線,以便為第一個因素自由估計系數。

對於第一個因素, []中的系數應該是23 對於第二個因素, []中的系數應該是13 而對於第三個因素, []中的系數應該是12

以前有沒有人有類似的東西?

謝謝!

如果我們想基於“ids”中的唯一數字部分創建單個vector ,請使用 lapply 循環唯一整數(“un1”),使用lapply提取與“ids”部分匹配的grep ,使用outer粘貼使用唯一值 ( setdiff ) 的unlist format ,並取消list以創建單個vector

un1 <- as.integer(unique(sub("_\\D+", "", ids)))
v1 <- unlist(lapply(un1, function(x) c(outer(grep(x, ids, value = TRUE), 
     setdiff(un1, x), FUN = function(u, v)
        sprintf('(%s, fixed[%d]) = 0.0;', u, v)))))
cat(paste(v1, collapse="\n"), "\n")
#(1_a, fixed[2]) = 0.0;
#(1_b, fixed[2]) = 0.0;
#(1_c, fixed[2]) = 0.0;
#(1_a, fixed[3]) = 0.0;
#(1_b, fixed[3]) = 0.0;
#(1_c, fixed[3]) = 0.0;
#(2_a, fixed[1]) = 0.0;
#(2_a, fixed[1]) = 0.0;
#(2_a, fixed[1]) = 0.0;
#(2_a, fixed[3]) = 0.0;
#(2_a, fixed[3]) = 0.0;
#(2_a, fixed[3]) = 0.0;
#(3_a, fixed[1]) = 0.0;
#(3_a, fixed[1]) = 0.0;
#(3_a, fixed[1]) = 0.0;
#(3_a, fixed[2]) = 0.0;
#(3_a, fixed[2]) = 0.0;
#(3_a, fixed[2]) = 0.0; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM