将tibble或data.frame中的两行合并(或扩展)为一行

时间:2018-01-03 17:03:40

标签: r dataframe reshape tidyverse

如何从中重塑:

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)) 

enter image description here

到此:

enter image description here

1 个答案:

答案 0 :(得分:1)

以下内容可能有效:

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列采用相同的名称,你可以重命名它们,虽然我认为这可能会令人困惑。