首页 > 解决方案 > 有没有更有效的方法将 24 列组合成一列作为 R 中的数组

问题描述

我在下面有一个代码,它可以获取 24 列(小时)的数据,并将其组合成一个单列数组,用于数据框中的每一行:

# Adds all of the values into column twentyfourhours with "," as the separator.
agg_bluetooth_data$twentyfourhours <- paste(agg_bluetooth_data[,1],
agg_bluetooth_data[,2], agg_bluetooth_data[,3], agg_bluetooth_data[,4],
agg_bluetooth_data[,5], agg_bluetooth_data[,6], agg_bluetooth_data[,7],
agg_bluetooth_data[,8], agg_bluetooth_data[,9], agg_bluetooth_data[,10],
agg_bluetooth_data[,11], agg_bluetooth_data[,12], agg_bluetooth_data[,13],
agg_bluetooth_data[,14], agg_bluetooth_data[,15], agg_bluetooth_data[,16],
agg_bluetooth_data[,17], agg_bluetooth_data[,18], agg_bluetooth_data[,19],
agg_bluetooth_data[,20], agg_bluetooth_data[,21], agg_bluetooth_data[,22],
agg_bluetooth_data[,23], agg_bluetooth_data[,24], sep=",")

但是,在此之后,我仍然需要编写更多代码行来删除空格、在空格周围添加括号并删除列。这些都不难做到,但我觉得应该有一个更短/更干净的代码来获得我正在寻找的结果。有没有人有什么建议?

标签: arraysr

解决方案


有一个内置功能要做rowSums。看起来你想要一个类似的rowPaste功能。我们可以这样做apply

# create example dataset
df <- data.frame(
    v=1:10,
    x=letters[1:10],
    y=letters[6:15],
    z=letters[11:20],
    stringsAsFactors = FALSE
)

# rowPaste columns 2 through 4
apply(df[, 2:4], 1, paste, collapse=",")

推荐阅读