英文:
R - pivot data frame with dynamic column names and no aggregation
问题
需要将数据框旋转并基于其中一列的值创建列。我的数据框如下所示:
REPORT_ID NBR CD abc_val item_name
752918618 LN AAA 5173 hours_start
752918618 LN AAA PO phase_start
752918618 LN AAA 5175 hours_end
752918618 LN AAA 1 ind_end
752918618 LN AAA 151447 cooldown
752918618 LN AAA TA phase_end
752918618 LN AAA 141151 start_time
752918618 LN AAA 1 ind_star
我需要以下结果。如您所见,添加了八列,列名为“abc_val”和“item_name”中的值。此外,在创建它们后,它们获得了来自abc_val
的值。
REPORT_ID NBR CD abc_valhours_start abc_valphase_start abc_valhours_end abc_valind_end abc_valcooldown abc_valphase_end abc_valstart_time abc_valstart_time abc_valind_star
752918618 LN AAA 5173 PO 5175 1 151447 TA TA 141151 1
创建数据框的代码也在此处:
REPORT_ID <- c(752918618,752918618,752918618,752918618,752918618,752918618,752918618,752918618)
NBR <- c("LN","LN","LN","LN","LN","LN","LN", "LN")
CD <- c("AAA","AAA","AAA","AAA","AAA","AAA","AAA", "AAA")
abc_val <- c("5173","PO", "5175", "1", "151447", "TA", "141151", "1")
item_name <- c("hours_start", "phase_start", "hours_end", "ind_end", "cooldown", "phase_end", "start_time", "ind_star")
df <- data.frame(REPORT_ID, NBR, CD, abc_val, item_name)
希望我的数据示例能够解释我所需要的内容
英文:
I need to pivot my data frame and create columns based on values in one of the columns. My data frame is as follows:
REPORT_ID NBR CD abc_val item_name
752918618 LN AAA 5173 hours_start
752918618 LN AAA PO phase_start
752918618 LN AAA 5175 hours_end
752918618 LN AAA 1 ind_end
752918618 LN AAA 151447 cooldown
752918618 LN AAA TA phase_end
752918618 LN AAA 141151 start_time
752918618 LN AAA 1 ind_star
and I need the below result. As you can see, eight columns were added with text "abc_val" and the value from column "item_name". Also, after they were created they got value from abc_val.
REPORT_ID NBR CD abc_valhours_start abc_valphase_start abc_valhours_end abc_valind_end abc_valcooldown abc_valphase_end abc_valstart_time abc_valstart_time abc_valind_star
752918618 LN AAA 5173 PO 5175 1 151447 TA TA 141151 1
The code for df creation is here as well:
REPORT_ID <- c(752918618,752918618,752918618,752918618,752918618,752918618,752918618,752918618)
NBR <- c("LN","LN","LN","LN","LN","LN","LN", "LN")
CD <- c("AAA","AAA","AAA","AAA","AAA","AAA","AAA", "AAA")
abc_val <- c("5173","PO", "5175", "1", "151447", "TA", "141151", "1")
item_name <- c("hours_start", "phase_start", "hours_end", "ind_end", "cooldown", "phase_end", "start_time", "ind_star")
df <- data.frame(REPORT_ID, NBR, CD, abc_val, item_name)
I hope the snapshot of my data explain what I am after
答案1
得分: 2
这应该解决了
library(tidyverse)
df %>%
mutate(item_name = item_name %>% str_c("abc_val", .)) %>%
pivot_wider(names_from = item_name, values_from = abc_val)
英文:
This should solve it
library(tidyverse)
df %>%
mutate(item_name = item_name %>% str_c("abc_val",.)) %>%
pivot_wider(names_from = item_name,values_from = abc_val)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论