1
$\begingroup$

How can I vectorize this code in R?

data <- data.frame(A = rep(5, 5), B = rep(0, 5))
data$abstract <- c("no abstract available", "A", "A", "B", "no abstract available")

for (row in (1:nrow(data))){
  data [row,"abstract"] <- gsub("no abstract available"," ",data[row,"abstract"])
}
$\endgroup$
1
  • 2
    $\begingroup$ Simple R programming questions like this are better asked on Stack Overflow. There are more R experts there and its a bit trivial to call this "Data Science" $\endgroup$
    – Spacedman
    Commented Dec 22, 2015 at 15:20

1 Answer 1

3
$\begingroup$

You have plenty of alternatives for this problem

  • Using sapply

    data$abstract <- sapply(data$abstract, 
                            function(x){gsub(pattern = "no abstract available",
                            replacement = " ", x)})
    
  • Using mapply

    data$abstract <- mapply(gsub, pattern = "no abstract available",
                            replacement = " ", data$abstract)
    
  • Using the stringr package

    library(stringr)
    data$abstract <- str_replace(data$abstract, "no abstract available", 
                                 " ")
    

Also, check this this question on StackOverflow for more information, like solutions with match and the qdap package.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.