R mapply到多个矩阵

时间:2015-07-24 05:16:49

标签: r matrix

假设我有三个矩阵

XMLHttpRequest cannot load http://localhost:8000/api/getContentByType?category=all. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5050' is therefore not allowed access

我想构建一个打印

的打印功能
public static void main(String args[])
{
    Map<String, Integer> wordcheck = new TreeMap<String, Integer>();
    String string1="world world is new world of kingdom of palace of kings palace";
    String string2[]=string1.split(" ");
    HashSet<String> set = new HashSet<String>();

    for (int i=0; i<string2.length; i++) 

     {
        String data=string2[i];
       for(int j=0;j<string2.length;j++)
       {
           if(i != j)
           {
            if(data.equalsIgnoreCase(string2[j]))
            {

                set.add(data);

            }
           }
       }

      }

    System.out.println("Duplicate word size :"+set.size());
    System.out.println("Duplicate words :"+set);


}

我正在考虑使用mapply,但mapply会返回单个值

col1 <- matrix(rep(c(1,2),each=5),5,ncol=2)
col2 <- matrix(rep(c(3,4),each=5),5,ncol=2)
col3 <- matrix(rep(c(5,6),each=5),5,ncol=2)

基本上,我想把矩阵的每一行作为一个整体来处理,但我无法弄清楚如何。

我知道我可以通过for循环执行此操作,但我试图避免这种情况。

TIA。

编辑 - 它并不是真正关于打印格式,而是将每个矩阵的每一行用作矢量输入集。

e.g。

1. (1,2),(3,4),(5,6)
2. (1,2),(3,4),(5,6)
3. (1,2),(3,4),(5,6)
4. (1,2),(3,4),(5,6)
5. (1,2),(3,4),(5,6)

2 个答案:

答案 0 :(得分:2)

如果这完全是关于打印格式的,那么这是一个应该有效的功能。我们使用paste()将元素组合成字符串,然后使用apply()在各个行中应用函数

foo <- function(..., .dots=list()) {
    dots<-c(list(...), .dots)
    x <- apply(sapply(dots, function(x) 
         paste0("(", apply(x,1,paste,collapse=","), ")")),
         1, paste, collapse=",")
    paste0(1:length(x), ". ", x, collapse="\n")
}

cat(foo(col1,col2,col3))
# 1. (1,2),(3,4),(5,6)
# 2. (1,2),(3,4),(5,6)
# 3. (1,2),(3,4),(5,6)
# 4. (1,2),(3,4),(5,6)
# 5. (1,2),(3,4),(5,6)

cat(foo(.dots=list(col1,col2,col3)))

答案 1 :(得分:0)

您可以使用Map()函数。

尝试以下方法:

f1 <- function(x) paste("(", paste(as.character(x), collapse = ","), ")", sep="")
f2 = unlist(Map(function(x) paste(x, ". ", paste(f1(col1[x,]), f1(col2[x,]), f1(col3[x,]), sep = ","), sep = ""), 1:nrow(col1)))
cat(f2, sep="\n")

这给出了所需的输出:

1. (1,2),(3,4),(5,6)
2. (1,2),(3,4),(5,6)
3. (1,2),(3,4),(5,6)
4. (1,2),(3,4),(5,6)
5. (1,2),(3,4),(5,6)