I'm trying to figure out a way to transpose data and then add that data to a seperate dataframe.
I have
Column 1 | Column 2| Column 3
________________________________
Data 1 | Data 2 | Data 3
And in a seperate data frame I have
actualColumn1| actualColumn2
________________________________
Column 1 | otherData 2
Column 2 | otherData 2
Column 3 | otherData 2
And want to get to:
actualColumn1| actualColumn2|addedData
________________________________
Column 1 | otherData 2 | Data 1
Column 2 | otherData 2 | Data 2
Column 3 | otherData 2 | Data 3
Since the column names from the first dataframe correspond perfectly to the rows in actualcolumn1
. I apologize if I didn't explain this very well. I'm still new to R/Shiny and dataframe manipulation.
CodePudding user response:
You can reshape the dataframe to have the 1 observation of 3 variables to 1 variable with 3 observations using pivot_longer()
, then join to the other dataframe.
library(tidyverse)
df1 %>%
mutate(x = 1) %>%
pivot_longer(cols = -x, names_to = "actualColumn1", values_to = "addedData") %>%
select(-x) %>%
left_join(x = df2, y = .)
# Joining, by = "actualColumn1"
# actualColumn1 actualColumn2 addedData
# 1: Column 1 otherData 2 Data 1
# 2: Column 2 otherData 2 Data 2
# 3: Column 3 otherData 2 Data 3
Data:
df1 <- data.table::fread("Column 1 | Column 2| Column 3
Data 1 | Data 2 | Data 3 ")
df2 <- data.table::fread("actualColumn1| actualColumn2
Column 1 | otherData 2
Column 2 | otherData 2
Column 3 | otherData 2 ")