【问题标题】:R create a matrixR 创建一个矩阵
【发布时间】:2012-01-17 23:43:27
【问题描述】:

我必须读取一些外部文件,提取一些列并用零补全缺失值。所以如果第一个文件在column$Name中有:a、b、c、d,并且column$Area有离散值;第二个文件在某些​​列中有:b、d、e、f 等等,对于其他文件,我需要创建一个这样的数据框:

        a      b      c      d      e   f
File1 value  value  value  value    0   0
File2   0    value    0    value  value  value

这是我为了更好地解释我的问题而编写的虚拟代码:

listDFs <- list()
for(i in 1:10){
    listDFs[[i]] <-
        data.frame(Name=c(
                   c(paste(sample(letters,size=2,replace=TRUE),collapse="")),
                   c(paste(sample(letters,size=2,replace=TRUE),collapse="")),
                   c(paste(sample(letters,size=2,replace=TRUE),collapse="")),
                   c(paste(sample(letters,size=2,replace=TRUE),collapse="")),
                   c(paste(sample(letters,size=2,replace=TRUE),collapse="")),
                   c(paste(sample(letters,size=2,replace=TRUE),collapse="")),
                   c(paste(sample(letters,size=2,replace=TRUE),collapse=""))),
                   Area=runif(7))
}
lComposti <- sapply(listDFs, FUN = "[","Name")
dfComposti <- data.frame(matrix(unlist(lComposti),byrow=TRUE))
colnames(dfComposti) <- "Name"
dfComposti <- unique(dfComposti)
                                        #
## The CORE of the code
lArea <- list()
for(i in 1:10){
    lArea[[i]] <-
        ifelse(dfComposti$Name %in% listDFs[[i]]$Name, listDFs[[i]]$Area, 0)}
                                        #
mtxArea <- (matrix(unlist(lArea),nrow=c(10),ncol=dim(dfComposti)[1],byrow=TRUE))

问题在于列名和每个值之间的“同步”。

你有什么建议吗?

如果我的代码结果不清楚,我也可以上传我使用的文件。

最好的

【问题讨论】:

    标签: r dataframe reshape


    【解决方案1】:

    最安全的方法是永远不要忘记名字:它们可能会以错误的顺序放回......

    您可以使用do.call(rbind, ...) 将所有data.frame 连接成一个高data.frame,然后使用dcast 将其转换为一个宽data.frame。

    # Add a File column to the data.frames
    names( listDFs ) <- paste( "File", 1:length(listDFs) )
    for(i in seq_along(listDFs)) {
      listDFs[[i]] <- data.frame( listDFs[[i]], file = names(listDFs)[i] )
    }
    
    # Concatenate them
    d <- do.call( rbind, listDFs )
    
    # Convert this tall data.frame to a wide one
    # ("sum" is only needed if some names appear several times 
    # in the same file: since you used "replace=TRUE" for the 
    # sample data, it is likely to happen)
    library(reshape2)
    d <- do.call( rbind, listDFs )
    d <- dcast( d, file ~ Name, sum, value.var="Area" )
    

    【讨论】:

    • 感谢您的建议!!!我解决了我的问题!!!我完全忽略了 reshape2 包,但现在我想我会仔细研究它!!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 2018-11-10
    相关资源
    最近更新 更多