[英]Combine two columns of different dataframes
I have the following 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 IE
word polarity
5 hello 0
10 red 0
17 hello 0
and和
x y
1607 hello 0.1
1743 red -0.3
I would like to combine these dataframes in such a way the desired result is:我想以这样的方式组合这些数据框,期望的结果是:
word polarity
5 hello 0.1
10 red -0.3
17 hello 0.1
We can use match
between the 'word' and 'x' column from 'df', 'df2', respectively to get the position, use that to extract the corresponding 'y' from 'df2'我们可以分别使用 'df' 和 'df2' 中的 'word' 和 'x' 列之间的match
来获取位置,使用它从 'df2' 中提取相应的 'y'
df$polarity <- df2$y[match(df$word, df2$x)]
-output -输出
df
word polarity
5 hello 0.1
10 red -0.3
17 hello 0.1
Here's a tidyverse solution, using left_join
.这是一个 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
Use a left join or inner join in dplyr.在 dplyr 中使用左连接或内连接。 you don't actually need to rename the columns beforehand.您实际上不需要事先重命名列。
new_df<-left_join(df1,df2, by = c("word" = "x))
You will have the extra column from the join because joins retain all columns you can either get rid of it before the join or after.您将从连接中获得额外的列,因为连接保留了所有列,您可以在连接之前或之后删除它。
###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.