我在下面有一个代码,它可以获取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=",")
另一种选择,使用@Dan Y的数据(如果您使用dput
发布了数据的子集,可能会有所帮助)。
library(tidyr)
library(dplyr)
df %>%
unite('new_col', v, x, y, z, sep = ',')
new_col
1 1,a,f,k
2 2,b,g,l
3 3,c,h,m
4 4,d,i,n
5 5,e,j,o
6 6,f,k,p
7 7,g,l,q
8 8,h,m,r
9 9,i,n,s
10 10,j,o,t
然后,您可以使用mutate
执行必要的编辑。在unite
调用中的列选择中也有相当大的灵活性。查看the select documentation.的“有用功能”部分