R:如何将单个列中包含的数据整理到单独的列中?

R: How to tidy data contained in a single column into separate columns?

我的数据框不整齐:

name   information
A      300 USD
A      70 kg
A      2 cm 
B      400 USD
B      90 kg
B      5 cm 

如何使用 dplyr、tidyr 和可能的其他软件包将 'information' 列整理成单独的 variables/columns:USD、kg 和 cm?

这是所需的输出:

name   USD    kg    cm
A      300    70    2
B      400    90    5

我们可以使用 tidyr 中的 separate/spreadseparate 将 'information' 列拆分为两列,然后在将 'unit' 更改为 factor 后,我们使用 spread 将其重塑为 'wide' 格式 class(以防列的顺序很重要)。

library(dplyr)
library(tidyr)
separate(df1, information, into = c("value", "unit")) %>% 
               mutate(unit= factor(unit, levels =unique(unit))) %>%
                spread(unit, value)
#  name USD kg cm
#1    A 300 70  2
#2    B 400 90  5

数据

df1 <- structure(list(name = c("A", "A", "A", "B", "B", "B"), information = c("300 USD", 
"70 kg", "2 cm", "400 USD", "90 kg", "5 cm")), .Names = c("name", 
"information"), class = "data.frame", row.names = c(NA, -6L))

这是另一个使用 tidyr 传播的例子:

假设我们有一个数据框 df,其中包含 'id'、'date'、'element' 和 'measurement' 的列:

df

id  date        element measurement

01  2018-02-06  tmax    55

01  2018-02-06  tmin    51

这个数据框不整齐,因为同一个 id '01' 有 2 行,而我们应该只有 1 行。我们可以使用 'spread' 跨列分布值 'tmax' 和 'tmin'。

df %>% spread(key=element, value=measurement)

id  date        tmax tmin

01  2018-02-06  55    51