arrays - 有没有更有效的方法将 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=",")
但是,在此之后,我仍然需要编写更多代码行来删除空格、在空格周围添加括号并删除列。这些都不难做到,但我觉得应该有一个更短/更干净的代码来获得我正在寻找的结果。有没有人有什么建议?
解决方案
有一个内置功能要做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=",")
推荐阅读
- postgresql - Postgres:如何执行 Sum 的查询,因为它给出了错误?
- apache - 基于txt文件的动态IP白名单
- linux - 在单行命令奇怪的 tty 中通过 ssh 运行 bash
- azure - Azure AD B2C REST API:创建批量本地帐户
- sql - 从 sql 查询创建 Informatica 映射
- css - 如何固定通量中一个元素的位置?
- ios - 我的应用在 xcode 11.4 中找不到 sirikit intentdefinition 类
- lda - LDA 模型中 0.3 的相干值
- sql - PLSQL使用数组从表中选择到变量中
- javascript - 如何在不渲染的情况下将 React 组件导出为 pdf