0

I would like to check if at least one element of my data_frame_1 is in data_frame_2 and add it like a new column

my code:

library(data.table)

object_to_check <- data.table(c('aaax', 'bbbx', 'cccy', 'dddk', 'mmmt'))
colnames(object_to_check) <- 'x'
list_of_element <- data.table(c('ax', 'kh', 'dk'))
colnames(list_of_element) <- 'y'

Fun2 <- function(element_to_find, string_to_check) {
   element_to_find <- '0'
      if (element_to_find == '0') {
         for (i in 1:length(list_of_element)) {
            m <- lista[i]
            element_to_find <- ifelse(grepl(m, string_to_check, ignore.case = T) == T,string_to_check,'')
         }
      }
   }

object_to_check <- object_to_check[, check := Fun2(check, x)]

my code give me this error:

Warning message:
In `[.data.table`(object_to_check, , `:=`(check, Fun2(check, x))) :
Adding new column 'check' then assigning NULL (deleting it).

I'm stuck on this error and i can't find a solution on my problem. Can sameone help me?

Desired output:

x check
aaax ax  
bbbx NA
cccx NA 
dddk dk  
mmmt NA 

Thanks

Matteo M
  • 68
  • 1
  • 9
  • https://stackoverflow.com/questions/3171426/compare-two-data-frames-to-find-the-rows-in-data-frame-1-that-are-not-present-in – Freak Jun 15 '17 at 09:33
  • Please show your expected output based on the example – akrun Jun 15 '17 at 09:34

1 Answers1

1

You can do it like this

> df1 <- data.frame(row.names=1:4, var1=c(TRUE, TRUE, FALSE, FALSE), var2=c(1,2,3,4))
> df2 <- data.frame(row.names=5:7, var1=c(FALSE, TRUE, FALSE), var2=c(5,2,3))
> df1
   var1 var2
1  TRUE    1
2  TRUE    2
3 FALSE    3
4 FALSE    4
> df2
   var1 var2
5 FALSE    5
6  TRUE    2
7 FALSE    3

There are also some other easiest ways are also available. you can use all.equal(target, current, ...) function. It does not sort the dataframes. Another way is to use identical() funtion

Freak
  • 6,786
  • 5
  • 36
  • 54
  • Thanks but i have to check if a string in df2 is contained in a larger string of df1. Identical can't solve my problem i have to use a regular expression to check if string_df2 is in string_df1 – Matteo M Jun 15 '17 at 09:57