从R中不同位置的字符串中提取字母

时间:2018-10-10 14:17:15

标签: r substr

我有两列,我想从不同的位置提取字母。目的是显示在Col2中使用了什么字母来替代Col1中的字母。字母将根据位置列从Col1和Col2中提取。在“位置”列中,字母“ E”表示将用于提取字母的位置。

enter image description here

这是我使用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

2 个答案:

答案 0 :(得分:1)

首先,我将创建一个辅助函数以从位置提取字符

subchr <- function(x, pos) {
  substring(x, pos, pos)
}

然后您可以找到要提取的所有位置

extract_at <- lapply(strsplit(as.character(df$Position), ""), 
    function(x) which(x=="E"))

将它们放在一起以获得所需的输出

mapply(function(e, a, b){
  paste(subchr(a, e), subchr(b,e), sep="|", collapse=" , ")
}, extract_at, as.character(df$Col1), as.character(df$Col2))
# [1] "S|O , r|u" "i|a , v|s" "e|a , t|q"

答案 1 :(得分:0)

也许是这样的:

export { default } from './App.component';

数据:

    public static string SerializeBindingToXmlString(Binding binding)
{
    var tempConfig = System.IO.Path.GetTempFileName();
    var tempExe = tempConfig + ".exe";
    var tempExeConfig = tempConfig + ".exe.config";
    using(System.IO.FileStream fs = new System.IO.FileStream(tempExe, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite))
    {

    }
    using (System.IO.FileStream fs = new System.IO.FileStream(tempExeConfig, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite))
    {
        fs.SetLength(0);
        using (System.IO.StreamWriter sr = new System.IO.StreamWriter(fs, System.Text.Encoding.UTF8)) {
            sr.WriteLine("<?xml version= \"1.0\" encoding=\"utf-8\" ?>");
            sr.WriteLine(@"<configuration />");
        }
    }

    var configuration = System.Configuration.ConfigurationManager.OpenExeConfiguration(tempExe);
    var contractGenerator = new System.ServiceModel.Description. ServiceContractGenerator(configuration);
    string bindingSectionName;
    string configurationName;
    contractGenerator.GenerateBinding(binding, out bindingSectionName, out configurationName);

   var bindingsSection =System.ServiceModel.Configuration.BindingsSection.GetSection(contractGenerator.Configuration);

    // this needs to be called in order for GetRawXml() to return the updated config
    // (otherwise it will return an empty string)
    contractGenerator.Configuration.Save();

    string xmlConfig = bindingsSection.SectionInformation.GetRawXml();
    System.IO.File.Delete(tempExeConfig);
    System.IO.File.Delete(tempExe);
    return xmlConfig;
}