1

I would like to create a text string from a dataframe, but specify which rows will add to the text string.

Here is an example dataframe:

x <- as.data.frame(matrix(nrow = 4, ncol = 2))
x$V1 <- c(1, 1, 1, 2)
x$V2 <- c("aa", "bb", "cc", 1)
x$V3 <- c(1, 2, 3, NA

I only want to build the text strings where x$V1 = 1. The result I am looking for is something like "aa 1 bb 2 cc 3", where the row where x$V1 = 2 is ignored for the building of the text string.

I have tried the following:

x$V4 <- for(i in 1:length(x$V1)){
  if (x[i, 1] == 1){
    paste(x[i,2], x[i,3])
  } else {""}
}
paste(x$V3, collapse = "")

The above code does not even create a V4 column in my dataframe.

Thanks for the help.

1
  • What should the new column look like? That same string repeated three times, then NA? Commented Oct 16, 2018 at 0:21

2 Answers 2

1

Here's a one line solution using base R -

do.call(paste, c(x[x$V1 == 1, -1], collapse = " "))

[1] "aa 1 bb 2 cc 3"
Sign up to request clarification or add additional context in comments.

Comments

0

You can use ifelse to do this. In general you can't assign from a for loop in the way you are attempting to do; you should assign from inside the loop. But it is much better to avoid loops.

x <- as.data.frame(matrix(nrow = 4, ncol = 2))
x$V1 <- c(1, 1, 1, 2)
x$V2 <- c("aa", "bb", "cc", 1)
x$V3 <- c(1, 2, 3, NA)

x$V4 = ifelse(x$V1 == 1, paste(x$V2, x$V3), "")
paste(x$V4, collapse = " ")
#> [1] "aa 1 bb 2 cc 3 "

Created on 2018-10-15 by the reprex package (v0.2.0).

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.