我有一个几乎完全空白的data.frame,但每行都有一个值.如何使用矢量化或其他r-locald方法将每行的内容合并为一个向量?
样本数据:
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"
)
Run Code Online (Sandbox Code Playgroud)
这是我尝试但它失败了,因为它返回一个二维矩阵而不是所需的向量:
raw_data$test <- apply(raw_data, MAR=1, FUN=paste0)
Run Code Online (Sandbox Code Playgroud)
您可以使用单个索引操作非常简单地执行此操作:
raw_data[raw_data!='']
Run Code Online (Sandbox Code Playgroud)
演示:
R> raw_data[raw_data!=''];
[1] "Millburn - Union" "Cranston (aka Garden City Center)" "Colorado Blvd" "Palo Alto" "Castro (aka Market St)"
Run Code Online (Sandbox Code Playgroud)
如果您关心矢量顺序是从上到下(而不是从左到右,然后从上到下,这就是上面的操作),您可以转置输入data.frame:
R> t(raw_data)[t(raw_data)!=''];
[1] "Palo Alto" "Castro (aka Market St)" "Cranston (aka Garden City Center)" "Millburn - Union" "Colorado Blvd"
Run Code Online (Sandbox Code Playgroud)
你的直觉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"
Run Code Online (Sandbox Code Playgroud)