How to extract same texts/values from 2 columns in R data frame?

╄→尐↘猪︶ㄣ 提交于 2019-12-14 02:26:41

问题


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")))

回答1:


An option using mapply as:

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

Data:

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


来源:https://stackoverflow.com/questions/50667902/how-to-extract-same-texts-values-from-2-columns-in-r-data-frame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!