'Create separate DF with data from original - remove original data at same time
I am trying to move test DF data to test2 DF data in one code chunk - Right now, I have this going as two separate code chunks - the top one creates the test2 data from test data. Then the bottom chunk simply removes that same data from test.
test2 <- test[0,colnames(test)]
test2 <- test[nchar(test$insert_text1) != 10 |
grepl(pattern = "text1", x = test$insert_text2`, ignore.case = T) == FALSE |
grepl(pattern = "text2", x = test$insert_text3, ignore.case = T) == TRUE |
is.na(test$insert_text1),]
test <- test[-c(nchar(test$insert_text1) != 10 |
is.na(test$insert_text1) |
grepl(pattern = "text2", x = test$insert_text2, ignore.case = T) == TRUE |
grepl(pattern = "text1", x = test$insert_text1, ignore.case = T) == FALSE) == FALSE,]
Thank you!
Solution 1:[1]
Creating a data frame and removing data from a data frame are 2 separate concepts - they should not be combined into one operation.
You can, however, simplify your code but moving the row identification to the top and not write/run the same logic twice. I've also done some other simplification: == FALSE
is a long way to write !
, == TRUE
is never needed (if x == TRUE
is TRUE
that means x
is already TRUE
), and I use with()
to skip the need for data$
in the command.
rows = with(test,
nchar(insert_text1) != 10 |
!grepl(pattern = "text1", x = insert_text2, ignore.case = T) |
grepl(pattern = "text2", x = insert_text3, ignore.case = T) |
is.na(insert_text1)
)
test2 = test[rows, ]
test = test[!rows, ]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Gregor Thomas |