gpt4 book ai didi

r - left_join 在具有不同列名的 for 循环中

转载 作者:行者123 更新时间:2023-12-04 10:21:29 24 4
gpt4 key购买 nike

我有一个名为 a 的 data.frame其结构类似于:-

a <- data.frame(X1=c("A", "B", "C", "A", "C", "D"),
X2=c("B", "C", "D", "A", "B", "A"),
X3=c("C", "D", "A", "B", "A", "B")
)

我还有另一套是:-
b <- data.frame(Xn=c("A", "B", "C", "D"),
Feature=c("some", "more", "what", "why"))

我要添加所有 Features从集合 b设置 a ,使得 X1 , X2X3在集合中具有相应的特征列 a .换句话说,集合 a 中的列变得:-
colnames(a) <- c("X1", "X2", "X3", "Features1", "Features2", "Features3")

如何在 for 循环中使用 left_join 来做到这一点?

最佳答案

在基础 R 中,我们可以 unlist a数据框和 match它与 b$Xn获取对应的Feature值(value)。我们可以cbind将此数据框转换为原始数据框以获得最终答案。

temp <- a
temp[] <- b$Feature[match(unlist(temp), b$Xn)]
names(temp) <- paste0('Feature', seq_along(temp))
cbind(a, temp)

# X1 X2 X3 Feature1 Feature2 Feature3
#1 A B C some more what
#2 B C D more what why
#3 C D A what why some
#4 A A B some some more
#5 C B A what more some
#6 D A B why some more

tidyverse ,我们可以得到长格式的数据,加入数据并把它恢复成宽格式。
library(dplyr)
library(tidyr)

a %>%
mutate(row = row_number()) %>%
pivot_longer(cols = -row) %>%
left_join(b, by = c('value' = 'Xn')) %>%
select(-value) %>%
pivot_wider(names_from = name, values_from = Feature) %>%
select(-row) %>%
rename_all(~paste0('Feature', seq_along(.))) %>%
bind_cols(a, .)

关于r - left_join 在具有不同列名的 for 循环中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60825257/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com