英文:
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 <- c("Ford", "Chevy", "Toyota", "Honda", "Nissan")
df |>
mutate(id = cumsum(value %in% make),
name = case_when(value %in% make ~ "Make",
grepl("\\d", value) ~ "Value",
T ~ "Model"))|>
pivot_wider(id_cols = id) |>
select(-id)
Output
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论