将两行合并(或扩展)成一行或 data.frame 成一行
Merge (or spread) two rows in a tibble or data.frame into one row
我如何完成重塑:
df_2row <- data.frame(ID = c("123", "123"), CURR = c("EUR", "USD"),
OtherCOls = c("abc", "abc"),
valueType1_EUR = c(100, NA), valueType2_CURR = c(NA, 110))
对此:
像下面这样的东西可以工作:
library(dplyr)
# create a separate subset data frame for each desired valueType/CURR combination
df.1 <- df_2row %>% select(ID, OtherCOls, valueType1_EUR, CURR) %>% na.omit()
df.2 <- df_2row %>% select(ID, OtherCOls, valueType2_CURR, CURR) %>% na.omit()
# join subsets together by ID & OtherCOls
df.combined <- left_join(df.1, df.2, by = c("ID", "OtherCOls"))
> df.combined
ID OtherCOls valueType1_EUR CURR.x valueType2_CURR CURR.y
1 123 abc 100 EUR 110 USD
如果您确实需要 CURR 列采用相同的名称,您可以重命名它们,但我认为这可能会造成混淆。
我如何完成重塑:
df_2row <- data.frame(ID = c("123", "123"), CURR = c("EUR", "USD"),
OtherCOls = c("abc", "abc"),
valueType1_EUR = c(100, NA), valueType2_CURR = c(NA, 110))
对此:
像下面这样的东西可以工作:
library(dplyr)
# create a separate subset data frame for each desired valueType/CURR combination
df.1 <- df_2row %>% select(ID, OtherCOls, valueType1_EUR, CURR) %>% na.omit()
df.2 <- df_2row %>% select(ID, OtherCOls, valueType2_CURR, CURR) %>% na.omit()
# join subsets together by ID & OtherCOls
df.combined <- left_join(df.1, df.2, by = c("ID", "OtherCOls"))
> df.combined
ID OtherCOls valueType1_EUR CURR.x valueType2_CURR CURR.y
1 123 abc 100 EUR 110 USD
如果您确实需要 CURR 列采用相同的名称,您可以重命名它们,但我认为这可能会造成混淆。