【发布时间】:2021-03-20 03:26:40
【问题描述】:
我在这里有一个包含此信息的数据框:
df <- data.frame("string1" = c("ABECDE","ABECDE","ABECDE"),
"string2" = c("ABCD","ABCD","ABCD"),
"site1" = NA, "site2" = NA, "combine" = NA, "filtered" = NA)
我想编写一个代码,在字符串中选择站点 E 和 D 并将它们添加到数据框中。 如果组合已经创建,我希望它返回并选择一个新组合并再次检查,直到它得到一个尚未选择的组合。
我在下面提供了我到目前为止所做的代码,它给出了以下输出:
string1 string2 site1 site2 combine filtered
1 ABECDE ABCD E3 D4 E3D4 E3D4
2 ABECDE ABCD E3 D4 E3D4 <NA>
3 ABECDE ABCD E3 D4 E3D4 <NA>
这里,E3D4 是你第一次通过函数时得到的值。 我现在希望它返回并选择下一个可能的组合: 接下来两行的 E6D4 和 D5D4 但我不知道如何正确地构造迭代。
这是我到目前为止的代码(可能有一种不太冗余的方式来编写它,但我是初学者,所以如果它过长,请见谅)
#make the columns of string1 and string2 into vectors
string1 <- df$string1
string2 <- df$string2
#for each string in the vector check to see first if it has an E, if not, then a D
#get the output as a letter and its position (eg E3)
for (i in 1:nrow(df)){
if (grepl("E", string1[i])){
sites1 = gregexpr('E', string1[i])
df$site1 <- paste0(substring(string1[i], sites1[[1]][1], sites1[[1]][1]), sites1[[1]][1])
} else if (grepl("D", string1[i])){
sites = gregexpr('D', string1[i])
df$site1 <- paste0(substring(string1[i], sites1[[1]][1], sites1[[1]][1]), sites1[[1]][1])
}
}
#do the same for the second vector
for (i in 1:nrow(df)){
if (grepl("E", string2[i])){
sites2 <- gregexpr('E', string2[i])
df$site2 <- paste0(substring(string2[i], sites2[[1]][1], sites2[[1]][1]), sites2[[1]][1])
} else if (grepl("D", string2[i])){
sites2 <- gregexpr('D', string2[i])
df$site2 <- paste0(substring(string2[i], sites2[[1]][1], sites2[[1]][1]), sites2[[1]][1])
}
}
#combine the sites
df$combine <- paste0(df$site1, df$site2)
#for each row of combined sites, check to see if the value is already created
for (i in 1:nrow(df)){
if(!df$combine[i] %in% df$filtered){
df$filtered[i] <- df$combine[i]
} else if(df$combine[i] %in% df$filtered){
#go back to for loop and look for either another E in the list
#if there is none, go to the next condition (looking for a D).
#pick the next possible values, put them together and check again
#do this continuously until you get a unique combine.
#do this for string1 and then string2 (or alternating both, which ever is easier)
}
}
【问题讨论】:
标签: r dataframe loops iteration conditional-statements