gpt4 book ai didi

r - 使用 apply 或其他矢量化方法合并列的内容

转载 作者:行者123 更新时间:2023-12-04 12:31:55 27 4
gpt4 key购买 nike

我有一个几乎完全空白的 data.frame,但每一行都有一个值。如何使用矢量化或其他 r-vernacular 方法将每行的内容合并为单个矢量?

样本数据:

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)

最佳答案

您可以使用单个索引操作非常简单地完成此操作:

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)"

如果您关心矢量顺序是从上到下(而不是从左到右然后从上到下,这就是上述操作所做的),您可以转置输入 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"

关于r - 使用 apply 或其他矢量化方法合并列的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29311836/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com