我有两个数据帧。一个是带有相应编号的单词库。另一个是一个问题,我有3个。我的原始数据在库中有200万行,还有100万个问题。至于为什么在列中使用for循环。我的问题是,为什么在合并命令中前两个带有数字的问题不排序,而只有单词的问题却不排序。任何可能的原因。我有可重现的数据,可能有很多代码,但是如果运行,它将在data.frames中更有意义。它应该全部工作,无需任何调整。 data.tables是df =问题,df2 =库,输出=我希望输出看起来像什么,而DF =是实际输出是什么。
words1<-c(1,2,3,"How","did","Quebec")
words2<-c(.24,.25,.66,"Why","does","volicty")
words3<-c("How","do","I","clean","a","car")
library<-c(1,3,.25,.66,"How","did","does","do","I","wash","a","Quebec","car","is")
embedding1<-c(.48,.68,.52,.39,.5,.6,.7,.8,.9,.3,.46,.48,.53,.42)
df <- data.frame(words1,words2,words3)
names(df)<-c("words1","words2","words3")
words1<-c(.48,NA,.68,.5,.6,.48)
words2<-c(NA,.52,.39,NA,.7,NA)
words3<-c(.5,.8,.9,NA,.46,.53)
output<-data.frame(words1,words2,words3)
#--------Upload 2nd dataset-------#
df2 <- data.frame(library,embedding1)
names(df2)<-c("library","embedding1")
#-----Find columns--------#
l=ncol(df)
l
mynames<-colnames(df)
head(mynames)
#------Combine and match libary to training data------#
require(gridExtra)
List = list()
for(name in mynames){
df1<-df[,name]
df1<-as.data.frame(df1)
x_train2<-merge(x= df1, y = df2,
by.x = "df1", by.y = 'library',all.x=T, sort=F)
new_x_train2<-x_train2[duplicated(x_train2[,2]),]
x_train2<-x_train2[,-1]
x_train2<-as.data.frame(x_train2)
names(x_train2) <- name
List[[length(List)+1]] = x_train2
}
list<-List
DF <- as.data.frame(matrix(unlist(list), nrow=length(unlist(list[1]))))
答案 0 :(得分:1)
您可以使用tidyverse
进行此操作。这样做可以在您的列中留下更多的NA,但可以保留顺序,我认为它基本上可以满足您的需求:
library(tidyverse)
library(reshape2)
df %>% melt(id = NULL) %>%
inner_join(.,df2, by = c("value" = "library")) %>%
spread(variable, embedding1) %>%
select(-value)
结果:
words1 words2 words3
1 NA 0.52 NA
2 NA 0.39 NA
3 0.48 NA NA
4 0.68 NA NA
5 NA NA 0.46
6 NA NA 0.53
7 0.60 NA NA
8 NA NA 0.80
9 NA 0.70 NA
10 0.50 NA 0.50
11 NA NA 0.90
12 0.48 NA NA
答案 1 :(得分:0)
主要原因是因为使用merge
可以完成排序。参见?merge
:
默认情况下,这些行是按字典顺序在公共列上排序的,但是对于sort = FALSE的排序是不确定的。
如果您逐步完成循环,则会看到它的实际效果。请改用dplyr::left_join
,以保留行顺序。
df1 <- df[, "words1"]
df1 <- as.data.frame(df1)
> df1
df1
1 1
2 2
3 3
4 How
5 did
6 Quebec
merge(x= df1, y = df2,
by.x = "df1", by.y = 'library', all.x=T, sort=F)
df1 embedding1
1 1 0.48
2 3 0.68
3 How 0.50
4 did 0.60
5 Quebec 0.48
6 2 NA
left_join(x = df1, y = df2, by = c("df1" = "library"), all.x = T)
df1 embedding1
1 1 0.48
2 2 NA
3 3 0.68
4 How 0.50
5 did 0.60
6 Quebec 0.48