![](/img/trans.png)
[英]replacing values of a dataframe column using values of a list and list name in R
[英]Replacing strings in dataframe with column name in R
我想替換 R dataframe 中的字符串。 當使用資源/生產步驟(列)時,dataframe 顯示每個生產訂單(行)。 對於此特定分析,不需要時間值,而是希望使用列名代替時間戳。
數據看起來像這樣
df_current <- data.frame(
Prod.order = seq(123, 127),
B100 = c("01:00:00", "02:00:00", "03:00:00", "04:00:00", "05:00:00"),
`B100 (2)` = c(NA, NA, "06:00:00", "07:00:00", NA),
D200 = c("02:00:00", NA, NA, NA, "06:00:00"),
D300 = c(NA, NA, "04:00:00", "05:00:00", "07:00:00"),
check.names = FALSE)
我希望它看起來像這樣。 (我也想刪除 NA,但這不是問題)
df_desired <- data.frame(
Prod.order = seq(123, 127),
B100 = c("B100", "B100", "B100", "B100", "B100"),
`B100 (2)` = c("", "", "B100 (2)", "B100 (2)", ""),
D200 = c("D200", "", "", "", "D200"),
D300 = c("", "", "D300", "D300", "D300"),
check.names = FALSE)
這似乎很簡單,但我一直無法弄清楚。 ps 如果該解決方案適合 dplyr 管道,那就太棒了;)
感謝:D
使用names(df)[col(df)]
復制列名的base
解決方案:
df_current[-1] <- ifelse(is.na(df_current), '', names(df_current)[col(df_current)])[, -1]
df_current
# Prod.order B100 B100 (2) D200 D300
# 1 123 B100 D200
# 2 124 B100
# 3 125 B100 B100 (2) D300
# 4 126 B100 B100 (2) D300
# 5 127 B100 D200 D300
或與t()
:
df_current[-1] <- t(ifelse(t(is.na(df_current)), '', names(df_current)))[, -1]
df_current
library(tidyverse)
df_current %>%
mutate(across(where(is.character), ~ifelse(is.na(.x), '', cur_column())))
Prod.order B100 B100..2. D200 D300
1 123 B100 D200
2 124 B100
3 125 B100 B100..2. D300
4 126 B100 B100..2. D300
5 127 B100 D200 D300
df_current %>%
pivot_longer(where(is.character)) %>%
mutate(value = ifelse(is.na(value), '', name)) %>%
pivot_wider()
# A tibble: 5 x 5
Prod.order B100 B100..2. D200 D300
<int> <chr> <chr> <chr> <chr>
1 123 B100 "" "D200" ""
2 124 B100 "" "" ""
3 125 B100 "B100..2." "" "D300"
4 126 B100 "B100..2." "" "D300"
5 127 B100 "" "D200" "D300"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.