使用apply或其他向量化方法合并列内容

5
我有一个数据框,几乎全部为空,但每行都有一个值。我怎样使用向量化的或其他r本地语言的方法将每行的内容合并为一个向量?
示例数据:
raw_data  <- structure(
    list(
        col1 = c("", "", "", "", ""),
        col2 = c("", "", "", "", ""),
        col3 = c("", "", "", "", ""),
        col4 = c("", "", "", "Millburn - Union", ""),
        col5 = c("", "", "Cranston (aka Garden City Center)", "",""),
        col6 = c("", "", "", "", ""),
        col7 = c("", "", "", "", ""),
        col8 = c("", "", "", "", "Colorado Blvd"), 
        col9 = c("", "", "", "", ""),
        col10 = c("", "", "", "", ""),
        col11 = c("Palo Alto",  "Castro (aka Market St)", "", "", "")
    ),
    .Names = c("col1", "col2", "col3", "col4", "col5", "col6", "col7", "col8", "col9", "col10", "col11"),
    row.names = c(5L, 4L, 3L, 2L, 1L),
    class = "data.frame"
)

这是我尝试过的,但它失败了,因为它返回的是一个二维矩阵,而不是所需的向量:
raw_data$test <-  apply(raw_data, MAR=1, FUN=paste0)
3个回答

5
您可以通过单个索引操作轻松完成此操作:
raw_data[raw_data!='']

示例:

R> raw_data[raw_data!=''];
[1] "Millburn - Union"                  "Cranston (aka Garden City Center)" "Colorado Blvd"                     "Palo Alto"                         "Castro (aka Market St)"

如果您关心向量顺序是从上到下(而不是从左到右然后从上到下,这就是上述操作所做的),您可以转置输入数据框:

R> t(raw_data)[t(raw_data)!=''];
[1] "Palo Alto"                         "Castro (aka Market St)"            "Cranston (aka Garden City Center)" "Millburn - Union"                  "Colorado Blvd"

3

关于apply的直觉是正确的。你只需要将collapse参数传递给paste函数:

 apply( raw_data, 1, paste0, collapse = "" )
                                  5                                   4                                   3 
                        "Palo Alto"            "Castro (aka Market St)" "Cranston (aka Garden City Center)" 
                                  2                                   1 
                 "Millburn - Union"                     "Colorado Blvd" 

1
在这个例子中,每行只有一个元素不是''。这里是另一种使用pastedo.call的方法。
do.call(paste, c(raw_data, sep=''))
#[1] "Palo Alto"                         "Castro (aka Market St)"           
#[3] "Cranston (aka Garden City Center)" "Millburn - Union"                 
#[5] "Colorado Blvd"    

假设在“raw_data”每行中有多个元素不为'',那么最好使用sep=';'或者,`。
raw_data[1,1] <- 'Millburn'
raw_data[1,3] <- 'Something'
gsub('^;+|;+$|(;);+', '\\1', do.call(paste, c(raw_data, sep=';')))
#[1] "Millburn;Something;Palo Alto"      "Castro (aka Market St)"     
#[3] "Cranston (aka Garden City Center)" "Millburn - Union"           
#[5] "Colorado Blvd"                    

apply 得到与上面相同的结果。

unname(apply(raw_data, 1, FUN=function(x) paste(x[x!=''],collapse=';')))
#[1] "Millburn;Something;Palo Alto"      "Castro (aka Market St)"    
#[3] "Cranston (aka Garden City Center)" "Millburn - Union"         
#[5] "Colorado Blvd"                    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接