【发布时间】:2018-10-10 14:17:14
【问题描述】:
我有两列,我想从不同位置提取字母。目标是显示在 Col2 中使用了哪个字母来替换 Col1 中的字母。字母将根据位置列从 Col1 和 Col2 中提取。在 Position 列中,字母“E”表示将用于提取字母的位置。
这是我尝试使用substr 函数:
df <- data.frame ("Col1" = c("Stores","University","Street","Street Store"),
"Col2" = c("Ostues", "Unasersity", "Straeq","Straeq Stuwq"),
"Position" = c("EMMEMM","MMEEMMMMMM", "MMMEME","MMMEMEMMMEEE"),
"Desired Output" = c("S|O , r|u","i|a , v|s","e|a , t|q", "e|a , t|q , o|u , r|w , e|q"))
n <- which(strsplit(df$Position,"")[[1]]=="E")
#output for the first row:
# [1] 1 4
#then I used substr function:
substr(df$Col1, n, n)
#only the first character returned as below:
[1] "S"
#desired output for first row:
S|O , r|u
【问题讨论】:
-
是的,前三列是输入的。我按照建议以可重现的格式添加了示例数据。
-
您的
position列似乎与示例第 1 行中的Col1和Col2不一致。第 2 行和第 3 行显示实际更改的每个字母的 E,而不仅仅是颜色不同的字母。在第一行中,前四个字母已从Col1更改为Col2。Position是否应该被视为给定的?还是在您的数据中计算得出? -
@brittenb 给出了位置列。我输入数据时打错了。
-
明白了。在这种情况下,@mrflick 有正确的解决方案。