本文介绍了如何从R数据框中的2列提取相同的文本/值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提取与col1和col2相同的文本/值,并创建数据框中提供的"desired_col".我尝试了几件事,但是没有用..

I want to extract text/value that is same in col1 and col2 , and create "desired_col" as provided in my data frame. I tried few things but did not work ..

mydata_1<-data.frame(col1=c("SL1234","SL786876"),col2=c("SL1334","SL78076"),desired_col=c(c("SL1","SL78")))

推荐答案

使用mapply的选项为:

mydata_1$matched <- mapply(function(x,y){
  # First take same length fron both columns
  x <- substring(x,1, min(nchar(x),nchar(y)))
  y <- substring(y,1, min(nchar(x),nchar(y)))

  matching_len <- which(strsplit(x, split = "")[[1]] != strsplit(y, split = "")[[1]])[1]-1
  substring(x, 1, matching_len)
}, mydata_1$col1, mydata_1$col2)


mydata_1
#       col1    col2 desired_col matched
# 1   SL1234  SL1334         SL1     SL1
# 2 SL786876 SL78076        SL78    SL78

数据:

mydata_1<-data.frame(col1=c("SL1234","SL786876"),
                     col2=c("SL1334","SL78076"),
                     desired_col=c(c("SL1","SL78")), 
                     stringsAsFactors = FALSE)

这篇关于如何从R数据框中的2列提取相同的文本/值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 10:28