![](/img/trans.png)
[英]r - matching of two dataframes and insertion of rows from one in another on condition
[英]R: adding matching vector values from two dataframes in one colomn
我有一個大致如下配置的數據框:
df <- cbind(c('hello', 'yes', 'example'),c(7,8,5),c(0,0,0))
字 | 頻率 | 數數 |
---|---|---|
你好 | 7 | 0 |
是的 | 8 | 0 |
例子 | 5 | 0 |
我想要做的是從不同的數據框中向第三列添加值,這很相似,但看起來像這樣:
df2 <- cbind(c('example','hello') ,c(5,6))
字 | 頻率 |
---|---|
例子 | 5 |
你好 | 6 |
我的目標是在兩個數據框中找到第一列的匹配值(它們具有相同的列名),並將第二個數據框中的匹配值添加到第一個數據框的第三列。
結果應如下所示:
df <- cbind(c('hello', 'yes', 'example'),c(7,8,5),c(6,0,5))
字 | 頻率 | 數數 |
---|---|---|
你好 | 7 | 6 |
是的 | 8 | 0 |
例子 | 5 | 5 |
到目前為止我嘗試過的是:
df <- merge(df,df2, by = "words", all.x=TRUE)
但是,它不起作用。
我可以使用一些幫助來理解它是如何完成的。 歡迎任何幫助。
這是一個“更新加入”。 我最喜歡的方法是在dplyr
中:
library(dplyr)
df %>% rows_update(rename(df2, count = frequency), by = "words")
在base R中,你可以做同樣的事情:
names(df2)[2] = "count2"
df = merge(df, df2, by = "words", all.x=TRUE)
df$count = ifelse(is.na(df$coutn2), df$count, df$count2)
df$count2 = NULL
這是data.table
的一個選項:
library(data.table)
setDT(df)[setDT(df2), on = "words", count := i.frequency]
輸出
words frequency count
<char> <num> <num>
1: hello 7 6
2: yes 8 0
3: example 5 5
或者在基礎 R 中使用match
:
df$count[match(df2$words, df$words)] <- df2$frequency
或者另一個使用left_join
tidyverse
coalesce
:
library(tidyverse)
left_join(df, df2 %>% rename(count.y = frequency), by = "words") %>%
mutate(count = pmax(count.y, count, na.rm = T)) %>%
select(-count.y)
數據
df <- structure(list(words = c("hello", "yes", "example"), frequency = c(7,
8, 5), count = c(0, 0, 0)), class = "data.frame", row.names = c(NA,
-3L))
df2 <- structure(list(words = c("example", "hello"), frequency = c(5, 6)), class = "data.frame", row.names = c(NA,
-2L))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.