将列分离/拆分为三个单独的列,当存在NA值时。

huangapple go评论74阅读模式
英文:

Separate/unstack column into three separate columns when there are NA values

问题

我有一列数据,看起来像这样:

value 
Ford
Focus
2,300
Chevy
15
Toyota
245
Honda
Nissan

我想要将它转换成这样的格式,希望使用tidyverse解决方案。谢谢!

Make   Model     Value   
Ford   Focus     2,300
Chevy  NA        15
Toyota NA        245
Honda  NA        NA
Nissan NA        NA
英文:

I have a column that looks like this

value 
Ford
Focus
2,300
Chevy
15
Toyota
245
Honda
Nissan

How would I get it to look like this? Would like to use a tidyverse solution. Thanks!

Make   Model     Value   
Ford   Focus     2,300
Chevy  NA        15
Toyota NA        245
Honda  NA        NA
Nissan NA        NA

答案1

得分: 1

你可以这样做(这依赖于完整的Make数据):

library(dplyr)
library(tidyr)

make <- c("Ford", "Chevy", "Toyota", "Honda", "Nissan")

df %>%
  mutate(id = cumsum(value %in% make),
         name = case_when(value %in% make ~ "Make",
                          grepl("\\d", value) ~ "Value",
                          TRUE ~ "Model")) %>%
  pivot_wider(id_cols = id) %>%
  select(-id)

输出结果

  Make   Model Value
  <chr>  <chr> <chr>
1 Ford   Focus 2,300
2 Chevy  NA    15   
3 Toyota NA    245  
4 Honda  NA    NA   
5 Nissan NA    NA   
英文:

You could do something like (this relies on complete data Make data):

library(dplyr)
library(tidyr)

make &lt;- c(&quot;Ford&quot;, &quot;Chevy&quot;, &quot;Toyota&quot;, &quot;Honda&quot;, &quot;Nissan&quot;)

df |&gt;
  mutate(id = cumsum(value %in% make),
         name = case_when(value %in% make ~ &quot;Make&quot;,
                          grepl(&quot;\\d&quot;, value) ~ &quot;Value&quot;,
                          T ~ &quot;Model&quot;))|&gt;
  pivot_wider(id_cols = id) |&gt;
  select(-id)

Output

  Make   Model Value
  &lt;chr&gt;  &lt;chr&gt; &lt;chr&gt;
1 Ford   Focus 2,300
2 Chevy  NA    15   
3 Toyota NA    245  
4 Honda  NA    NA   
5 Nissan NA    NA   

huangapple
  • 本文由 发表于 2023年8月9日 01:25:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76861905.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定