[英]Replacing values in a vector with values from another vector in R
我在用另一個向量中的值替換向量中的值時遇到麻煩。 基本的程序邏輯是這樣的:
例如,我的關鍵字列表如下所示
能力
開發
環境...
我最大的出現向量是從關鍵字列表創建的,並像這樣初始化
能力0
開發0
環境0
現在我正在將最大出現矢量與CSV文件進行比較
能力3
開發5
環境4
能力5
開發7
環境1
因此,基本上我想用文件1和2中的最大值填充最大出現向量。例如,在最大出現向量中,ENVIRONMENTAL的最大出現應更改為4(掃描文件1和文件2之后的最大出現)。 這是我的代碼:
# Find the largest frequency of the given keywords by searching the keyword sets
# Start by defining and initializing the max occurence vector
keywordslength=length(keywords)
keywordmax=data.frame(keywords)
keywordmax$Max=0
# Start by reading the keyword set and keeping the frequency of the keyword
ksearch1=read.csv("set1.csv",header=FALSE,sep=",")
ksearch1$V1=toupper(ksearch1$V1)
# Now scan ksearch1 for the word in question
for (i in 1:keywordslength)
{
# Establish the keyword
testkey=keywords[i]
testmax=0
# Scan ksearch1
for (j in 1:length(ksearch1$V1))
{
if (ksearch1[j,1]==testkey)
{
testmax=ksearch1[j,2]
}
if (subset(keywordmax, keywords==testkey, select=c(Max))>=testmax)
{
keywordmax[which(keywords==testkey),2]=testmax
}
}
}
這應該工作
創建關鍵字列表和兩個文件
keywords <- as.data.frame(c("Ability","Develops","Environmental"))
max_occur <- data.frame(keywords,c(0,0,0))
file1 <- data.frame(keywords,c(3,5,4))
file2 <- data.frame(keywords,c(5,7,1))
適當地重命名列
colnames(file1) <- c("V1","V2")
colnames(file2) <- c("V1","V2")
colnames(keywords) <- c("V1")
colnames(max_occur) <- c("V1","V2")
根據關鍵字對數據幀進行排序
keywords <- as.data.frame(keywords[sort(keywords$V1,decreasing = FALSE),])
max_occur <- as.data.frame(max_occur[sort(max_occur$V1,decreasing = FALSE),])
file1 <- file1[sort(file1$V1,decreasing=FALSE),]
file2 <- file2[sort(file2$V1,decreasing=FALSE),]
重命名它們,因為它們已轉換為因子
colnames(keywords) <- c("V1")
colnames(max_occur) <- c("V1","V2")
找到最大值並存儲在max_occur
for(i in 1:length(keywords$V1)){
max_occur$V2[i] <- max(max_occur$V2[i],file1$V2[i],file2$V2[i])
}
讓我知道每個文件中是否都沒有所有關鍵字。 我會稍微更改代碼。 根據您發布的內容。 它們都出現在每個文件中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.