[英]Combine two columns of different dataframes
我有以下數據框:
> dput(df)
structure(list(word = c("hello", "red", "hello"), polarity = c(0, 0, 0)), row.names = c(5L, 10L, 17L), class = "data.frame")
> dput(df2)
structure(list(x = c("hello", "red"), y = c(0.1, -0.3)), row.names = c(1607, 1743), class = "data.frame")
IE
word polarity
5 hello 0
10 red 0
17 hello 0
和
x y
1607 hello 0.1
1743 red -0.3
我想以這樣的方式組合這些數據框,期望的結果是:
word polarity
5 hello 0.1
10 red -0.3
17 hello 0.1
我們可以分別使用 'df' 和 'df2' 中的 'word' 和 'x' 列之間的match
來獲取位置,使用它從 'df2' 中提取相應的 'y'
df$polarity <- df2$y[match(df$word, df2$x)]
-輸出
df
word polarity
5 hello 0.1
10 red -0.3
17 hello 0.1
這是一個 tidyverse 解決方案,使用left_join
。
library(tidyverse)
df1 %>%
# Remove polarity column from df1
select(-polarity) %>%
# Left join using the word column
# First you'll need to rename the x column in df2 to be the same in df1 (i.e., word)
left_join(df2 %>%
rename("word" = x),
# The name of the column to use for the left join
by = "word")
# word y
#1 hello 0.1
#2 red -0.3
#3 hello 0.1
在 dplyr 中使用左連接或內連接。 您實際上不需要事先重命名列。
new_df<-left_join(df1,df2, by = c("word" = "x))
您將從連接中獲得額外的列,因為連接保留了所有列,您可以在連接之前或之后刪除它。
###Before the join run this
df1$polarity = NULL
####join
names(new_df)<- c("word", "polarity")
#### if performed after the join
new_df$polarity = NULL
names(new_df)<- c("word", "polarity")
你可以使用 df$polarity<-df2$y
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.