Ad
R/Shiny: Transpose And Add Data To Dataframe
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.
Ad
Answer
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 ")
Ad
source: stackoverflow.com
Related Questions
- → OctoberCMS Backend Loging Hash Error
- → "failed to open stream" error when executing "migrate:make"
- → OctoberCMS - How to make collapsible list default to active only on non-mobile
- → Create plugin that makes objects from model in back-end
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → How to install console for plugin development in October CMS
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → How to update data attribute on Ajax complete
- → October CMS - Conditionally Load a Different Page
Ad