我試圖找出一種轉置資料的方法,然后將該資料添加到單獨的資料幀中。
我有
Column 1 | Column 2| Column 3
________________________________
Data 1 | Data 2 | Data 3
在一個單獨的資料框中,我有
actualColumn1| actualColumn2
________________________________
Column 1 | otherData 2
Column 2 | otherData 2
Column 3 | otherData 2
并想到達:
actualColumn1| actualColumn2|addedData
________________________________
Column 1 | otherData 2 | Data 1
Column 2 | otherData 2 | Data 2
Column 3 | otherData 2 | Data 3
由于第一個資料框中的列名與actualcolumn1. 如果我沒有很好地解釋這一點,我深表歉意。我還是 R/Shiny 和資料幀操作的新手。
uj5u.com熱心網友回復:
您可以使用 重塑資料框,將 3 個變數的 1 個觀察值轉換為 3 個觀察值的 1 個變數pivot_longer(),然后加入另一個資料框。
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
資料:
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 ")
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/397799.html
上一篇:在多列上使用%in%運算子
