简体   繁体   English

R 将列中的数值向量拆分为多列

[英]R Split numeric vector in a column into multiple columns

I have a dataframe that has numeric vector in a column and want to split the column into multiple columns.我有一个数据框,在一列中有数字向量,并希望将该列拆分为多列。 An example is given below for dataframe df with two columns a and b .下面给出了具有两列ab数据帧df的示例。 Each column is composed of a vector of x and y values.每列由xy值的向量组成。 I want to separate the numeric vectors into two columns x and y .我想将数字向量分成两列xy The example only has two columns a and b but could have more.该示例只有两列ab但可以有更多列。

What I found so far is that one can use tidyr:separate separate string based vector but not numeric vector.到目前为止,我发现可以使用 tidyr:separate 单独的基于字符串的向量,但不能使用数字向量。 A similar question was also asked in this post for string based vector.这篇文章中也针对基于字符串的向量提出了类似的问题。 R Split a column containing a vector into multiple columns . R 将包含向量的列拆分为多列 Another question was asked in this post which is directly related.在这篇文章中提出了另一个直接相关的问题。 https://community.rstudio.com/t/split-a-column-each-element-is-a-vector-to-multiple-columns/14009/6 . https://community.rstudio.com/t/split-a-column-each-element-is-a-vector-to-multiple-columns/14009/6 I was wondering if there are better ways.我想知道是否有更好的方法。

df <- tribble(
  ~a, ~b,
  c(1.2, 2.3), c(1.3, 2.4),
  c(3.4, 4.5), c(5.6, 7.8))

Expected dataframe would be a dataframe with four columns.预期的数据框将是具有四列的数据框。

a.x   a.y   b.x   b.y
1.2   2.3   1.3   2.4
3.4   4.5   5.6   7.8

This is a little ugly but should work:这有点难看,但应该有效:

df %>% 
  mutate_all(~ map_chr(., paste, collapse = ",")) %>% 
  separate(a, into = c("a.x", "a.y"), sep = ",") %>% 
  separate(b, into = c("b.x", "b.y"), sep = ",") %>% 
  mutate_all(as.numeric)

我在这里借用了马库斯的回答。

as.data.frame(lapply(df, function(x) t(do.call(cbind, x))))

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

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