简体   繁体   English

将所有列与tidyr一起使用

[英]Unite all columns in tibble with tidyr

I want to unite all the columns in a tibble into one for later processing. 我想将小标题中的所有列合并为一个,以便以后处理。 Whenever I attempt to do this, I get the error 每当我尝试执行此操作时,都会收到错误消息

Error in if (!after) c(values, x) else if (after >= lengx) c(x, values) else c(x[1L:after], : missing value where TRUE/FALSE needed if(!after)c(values,x)else(如果> after> = lengx)c(x,values)else c(x [1L:after],:缺少需要TRUE / FALSE的值时出错

The tidyr:unite documentation says you can do this by not specifying any columns. tidyr:unite文档说您可以通过不指定任何列来做到这一点。 Here's a toy example: 这是一个玩具示例:

ex <- as_tibble(matrix(rnorm(20), ncol = 4))
ex
unite(ex, 'new')

Am I just missing some tidyverse subtlety or...? 我只是想念一些tidyverse的精妙之处还是...?

How about 怎么样

df <- ex %>%
unite(ex,1:ncol(ex),sep=" ") 

So, I believe you need to specify the columns even if you want to combine all of them. 因此,我相信即使您要合并所有列,也需要指定列。

To do this, you can just use 1:x where x is the last column number, you don't need to write them all out. 为此,您可以只使用1:x,其中x是最后一个列号,您无需全部写出来。 For example, in your code you would put: 例如,在您的代码中应输入:

unite(ex, new, 1:4, sep="")

Remember to put the sep= argument in as well - sep="" means they'll be joined together with no gaps, but sep="." 切记也要输入sep =参数-sep =“”表示它们将无间隙地连接在一起,但是sep =“。 means there will be a dot in between. 表示两者之间会有一个点。

Hope that is still of use! 希望仍然有用!

edit: to make it easier to use the column numbers instead of names, you can use ncol() to find the number of columns to specify, eg ncol(ex) returns 4 in your example. 编辑:为了使使用列号代替名称更容易,可以使用ncol()查找要指定的列数,例如,ncol(ex)在您的示例中返回4。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM