【发布时间】:2017-02-21 08:07:41
【问题描述】:
我对 R 中的代码有疑问。
我有一个包含 4 列和超过 600k 观察值的数据集(问题),其中一列名为“V3”。 本专栏有诸如“今天是什么日子?”之类的问题。 我有第二个数据集(voc),有 2 列,其中一列名称为“单词”,另一列名称为“同义词”。如果在我的第一个数据集(问题)中存在来自“同义词”列的第二个数据集(voc)的单词,那么我想将其替换为“单词”列中的单词。
questions = cbind(V3=c("What is the day today?","Tom has brown eyes"))
questions <- data.frame(questions)
V3
1 what is the day today?
2 Tom has brown eyes
voc = cbind(word=c("weather", "a","blue"),synonyms=c("day", "the", "brown"))
voc <- data.frame(voc)
word synonyms
1 weather day
2 a the
3 blue brown
Desired output
V3 V5
1 what is the day today? what is a weather today?
2 Tom has brown eyes Tom has blue eyes
我写了简单的代码,但它不起作用。
for (k in 1:nrow(question))
{
for (i in 1:nrow(voc))
{
question$V5<- gsub(do.call(rbind,strsplit(question$V3[k]," "))[which (do.call(rbind,strsplit(question$V3[k]," "))== voc[i,2])], voc[i,1], question$V3)
}
}
也许有人会帮助我? :)
我写了第二个代码,但它也不起作用..
for( i in 1:nrow(questions))
{
for( j in 1:nrow(voc))
{
if (grepl(voc[j,k],do.call(rbind,strsplit(questions[i,]," "))) == TRUE)
{
new=matrix(gsub(do.call(rbind,strsplit(questions[i,]," "))[which(do.call(rbind,strsplit(questions[i,]," "))== voc[j,2])], voc[j,1], questions[i,]))
questions[i,]=new
}
}
questions = cbind(questions,c(new))
}
【问题讨论】:
-
您的问题不太可能吸引答案,请提供一些示例数据(涉及的数据帧的前几行),期望输出的示例也很好。
-
好的! :) 谢谢你的建议